When printing a char array, why is `*` not used?

For instance:

#include <stdio.h>

const int MAX = 3;

int main () {

   int  var[] = {10, 100, 200};
   int i, *ptr[MAX];

   for ( i = 0; i < MAX; i++) {
      ptr[i] = &var[i]; /* assign the address of integer. */
   }

   for ( i = 0; i < MAX; i++) {
      printf("Value of var[%d] = %d\n", i, *ptr[i] );
   }

   return 0;
}

In the above code, it is *ptr[i]used to print values, where, as when using an array of pointers to a character, as in the example below, it is used only name[i], not with*

#include <stdio.h>

const int MAX = 4;

int main () {

   char *names[] = {
      "Zara Ali",
      "Hina Ali",
      "Nuha Ali",
      "Sara Ali",
   };

   int i = 0;

   for ( i = 0; i < MAX; i++) {
      printf("Value of names[%d] = %s\n", i, names[i] );
   }

   return 0;
}
+4
source share
2 answers

As informaticienzerowith when using printf(...)with %d, printf(...)expects you to provide a value int. However, printf(...)c %swants you to specify a value char*.

In your case:

ptr=> int**, so ptr[i]=> int*and *ptr[i]=>int

names = > char**, names[i] = > char*.

printf(...) char* , \0, "". , sizeof . MAX. , sizeof . , .

+4

, names[i] char*, , printf("%s"). *, char.

, ptr[i] int*. , printf("%d") int, a * ptr.

+2

Source: https://habr.com/ru/post/1664989/


All Articles