Reputation: 1
I'm trying to learn C and having trouble accessing the data from a pointer of the data.
I have the example code:
// character array for string
char mystring[] = "Hello";
// store mystring's pointer
int p = *mystring;
printf("String to pointer is %d\n":, p);
>> String to pointer is: 1819043144
// trying to access data from pointer p
printf("%s",&p);
>> H
Why does this just "H" just get printed when I try and access the data from pointer p using the & operator?
Upvotes: 0
Views: 2135
Reputation: 780818
The expression &p
has nothing to do with mystring
. p
is an integer variable, and &p
is the address of that variable.
int p = *mystring;
is equivalent to:
int p;
p = *mystring;
*mystring
is the first element of the mystring
array, which is the character 'H'
. So this is equivalent to:
int p = 'H';
Your variable initialization is simply making a copy of the first character of mystring
and putting that in p
. It also converts it from a char
to int
.
When you try to print p
using %s
format, you're causing undefined behavior, because %s
requires the corresponding argument to be a pointer to a null-terminated string, and you've given it a pointer to an int
.
Compare your code with this:
int *p = mystring;
printf("%s", p);
This is closer to correct, because now p
is a pointer, and it does point to the string. It's not a copy of anything. But it's still incorrect because the argument for %s
must be char *
, not int *
. So you need to convert it:
printf("%s", (char *)p);
But the most proper way to do it is the declare p
as the correct pointer type in the first place:
char *p = mystring;
printf("%s", p);
Upvotes: 3