Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Confused with syntax of String pointer to print values

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

  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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading