Click here to Skip to main content
15,889,877 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi. Can someone explain me why I cant make my pointer point to address of an array ?
C++
int main()
{
	char s[] = "string";
	char *p = &s;


    return 0;
}


But this works:
C++
int main()
{
	char s[] = "string";
	char *p = s;


    return 0;
}


And also Can someone explain me how this for loop works ?
C++
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
Posted
Updated 13-Jul-17 0:01am
v2

1 solution

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
 
Share this answer
 
Comments
The_Unknown_Member 13-Jul-17 6:44am    
I also have another question. Lets say I have this array: char s[] = "string";
Since the arrays in C++ are pointers to a data in the memory and since the char is 1 byte so doing s[1] should be the same as s + 1 right ? But it does not compile ? Why ?
OriginalGriff 13-Jul-17 7:05am    
That's going to depend on what - exactly - you are trying to compile.
If it's this:

printf("%c%c", s[0], s[1]);

Then it will compile, and it'll work - it will print the first two characters.
What code are you getting compilation problems with?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900