C\C++ 指针问题 求大家解答
本帖最后由 counting_stars 于 2015-12-24 21:42 编辑下面是写的一个求最长字符串的程序
#include<iostream>
#include<cstdlib>
char ** max(char *arr[], int n);
int main(void)
{
using namespace std;
char *a = {
"qwer",
"asdfg",
"lkjnhgfa",
"dsdsaf"
};
cout << "a = " << a << endl;
cout << "a = " << a << endl;
cout << "a = " << a << endl;
cout << "a = " << a << endl;
cout << "-------------------------------------" << endl;
cout << "&a = " << &a << endl;
cout << "&a = " << &a << endl;
cout << "&a = " << &a << endl;
cout << "&a = " << &a << endl;
cout << "-------------------------------------" << endl;
cout << "最长:" << *max(a, 4) << endl;
cout << "地址:" <<max(a, 4) << endl;
system("pause");
return 0;
}
char ** max(char *arr[], int n) //返回最长的字符串
{
char **temp = arr;
for (int i = 1; i < n; i++)
{
if (strlen(*temp) < strlen(arr))
*temp = arr;
}
return temp;
}
为什么从max中返回的指针用一次解除引用,得到的是char * 数组首元素地址而不是最长的那个字符串的地址呢?{:9_241:} #include<iostream>
#include<cstdlib>
char ** max(char *arr[], int n);
int main(void)
{
using namespace std;
char *a = {
"qwer",
"asdfg",
"lkjnhgfa",
"dsdsaf"
};
cout << "a = " << a << endl;
cout << "a = " << a << endl;
cout << "a = " << a << endl;
cout << "a = " << a << endl;
cout << "-------------------------------------" << endl;
cout << "&a = " << &a << endl;
cout << "&a = " << &a << endl;
cout << "&a = " << &a << endl;
cout << "&a = " << &a << endl;
cout << "-------------------------------------" << endl;
cout << "最长:" << *max(a, 4) << endl;
cout << "地址:" << max(a, 4) << endl;
cout << "-------------------------------------" << endl;
cout << "a = " << a << endl;
cout << "a = " << a << endl;
cout << "a = " << a << endl;
cout << "a = " << a << endl;
return 0;
}
char ** max(char *arr[], int n) //返回最长的字符串
{
char **temp = arr;
for (int i = 1; i < n; i++)
{
if (strlen(*temp) < strlen(arr))
*temp = arr;
}
return temp;
}
//你一不小心把原数组给改了,圣诞快乐! Delta 发表于 2015-12-25 09:46
#include
#include
char ** max(char *arr[], int n);
{:9_220:}好像是这么回事谢谢圣诞节快乐 大神,为了50鱼币拼了 mobai 看懵了.. 看看, 果然c指针很重要
页:
[1]