I just learned pointers and I am quite confused with the syntax.
In my code, I've created a pointer variable ptr_int that points to int x[]. To print the value of the first element in the array, I would *ptr_int To print the address of the first element in the array, I would use ptr_int
However, now I create a pointer variable str_ptr that points to an array of characters (string).
My question is,
Why can't I use *str_ptr to print the value of the first element in the array?
Why can't I use str_ptr to print the address of the first element in the array?
Why does str_ptr prints out the entire String? Doesn't str_ptr points to the address of the first element only?
int x[5] = {1, 2, 3, 4, 5}; int *ptr_int; ptr_int = x; printf("\n\n The address of ptr_int is: %u", ptr_int); printf("\n The value of ptr_int is: %d", *ptr_int); char *str_ptr = "Character string to be printed"; // Confused?? printf("\n %s", str_ptr);
My expected output for str_ptr
- *str_ptr = C
- str_ptr = <address of first element, C>
Actual output
CodePudding user response:
- The format string
%p
is used to print void pointers. So it should be:
printf("\n\n The address of ptr_int is: %p", (void *) ptr_int);
- If you want to print the first character you need to do either:
printf("%c\n", *str_ptr); // or
printf("%.1s\n", str_ptr);
- In order to print the address of the first element in the array you would do:
printf("%p\n", (void *) str_ptr); // or
printf("%p\n", (void *) &str_ptr[0]);
- A pointer to array points to the whole array. Pointer to first element of array points to a single value. Both pointers point to same memory address.