Home > Net >  Confused with syntax of String pointer to print values
Confused with syntax of String pointer to print values

Time:10-30

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,

  1. Why can't I use *str_ptr to print the value of the first element in the array?

  2. Why can't I use str_ptr to print the address of the first element in the array?

  3. 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

  1. *str_ptr = C
  2. str_ptr = <address of first element, C>

Actual output

enter image description here

CodePudding user response:

  1. 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);
  1. If you want to print the first character you need to do either:
printf("%c\n", *str_ptr); // or
printf("%.1s\n", str_ptr);
  1. 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]);
  1. 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.
  • Related