[C ++]指向数组的指针? [英] [C++] pointer to an array ?

查看:105
本文介绍了[C ++]指向数组的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。有人可以解释我为什么我不能让我的指针指向数组的地址?

  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 a char, so &s is a pointer to a pointer to a char. You would need to change the type of p to use the address of s:

char s[] = "string";
char **p = &s;


This works:

char s[] = "string";
char *p = s;

because s is a pointer to a char, and so is p


这篇关于[C ++]指向数组的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆