[C ++]指向数组的指针? [英] [C++] pointer to an array ?
问题描述
您好。有人可以解释我为什么我不能让我的指针指向数组的地址?
int main()
{
char s [] = string;
char * p =& s;
return 0 ;
}
但这样可行:
int main()
{
char s [] = string;
char * p = s;
return 0 ;
}
还有人可以解释一下这个for循环是如何工作的吗?
int main()
{
char s [] = string;
for ( char * cp = s; * cp; cp ++)
{
printf( element%c \ n,* cp) ;
}
return 0 ;
}
我的尝试:
在CodeProject.com中提出问题
你不能这样做:
char s [] =string;
char * p =& s;
因为数组的名称是指向该数组的第一个元素的指针。所以
s
已经是指向char
的指针,所以& s
是指向char
的指针。您需要更改p
的类型才能使用s
的地址:
char s [] =string;
char ** p =& s;
这样有效:
char s [] =string;
char * p = s;
因为
s
是指向char
的指针,所以p
Hi. Can someone explain me why I cant make my pointer point to address of an array ?
int main()
{
char s[] = "string";
char *p = &s;
return 0;
}
But this works:
int main()
{
char s[] = "string";
char *p = s;
return 0;
}
And also Can someone explain me how this for loop works ?
int main()
{
char s[] = "string";
for (char *cp = s; *cp; cp++)
{
printf("element %c \n", *cp);
}
return 0;
}
What I have tried:
Asking question here in CodeProject.com
You can't do this:
char s[] = "string"; char *p = &s;because the name of an array is a pointer to the first element of that array. So
s
is already a pointer to achar
, so&s
is a pointer to a pointer to achar
. You would need to change the type ofp
to use the address ofs
:
char s[] = "string"; char **p = &s;
This works:
char s[] = "string"; char *p = s;because
s
is a pointer to achar
, and so isp
这篇关于[C ++]指向数组的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!