Reputation: 55
So I need to have a pointer to a value in a const char array. But I can't quite get it to work without errors. Here's the code.
int main (void)
{
const char *alp = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char *ptr = &alp[3];
printf("%s\n", ptr);
return 0;
}
Edit- Sorry for not mentioning the errors. The thing is I get tons of different errors depending on where I put different asterisks and ampersands. There is no one particular error. One of the more frequent ones I get says "incompatible integer to pointer conversion assigning to 'char *' from 'const char';"
In the end I just want "ptr" to be equal to a pointer pointing to "D" in the array "alp".
Upvotes: 1
Views: 754
Reputation: 10502
alp
is a pointer to constant char
.
ptr
is a pointer to a non-const char
.
If you want that to work out you would need to change ptr
to be defined as:
char const * ptr = &alp[3];
Upvotes: 2
Reputation: 3905
The const is saying that you're not going to change it, but then you're trying to copy the reference to a variable without that limitation. Instead, try:
const char *ptr = &alp[3];
But note that as other posters have already suggested, this code will give you a pointer to a string beginning with the D (e.g. DEFGHI...), not just the character D.
Upvotes: 0
Reputation: 2662
If you only want one character to print, change the %s
to %c
and dereference the pointer
printf("%c\n", *ptr);
It's true that you had a character pointer but %s
tells printf to print from that pointer until it reads a null character. So we switch to %c
which will print one character but it expects a value rather than a pointer to a value.
Upvotes: 4