Step
Step

Reputation: 307

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

For example:

#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 *ptr[i] is used to print the value where as when a array of pointers to character is used as in the below example only name[i] is used and 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;
}

Upvotes: 4

Views: 88

Answers (2)

FrogTheFrog
FrogTheFrog

Reputation: 1671

Like informaticienzero said, when using printf(...) with %d, printf(...) expects you to provide an int value. However printf(...) with %s wants you to provide a char* value.

In your case:

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

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

printf(...) then uses char* to iterate over characters until it finds \0 character which is basically "the end". Also, when working with constant size arrays, try to use sizeof operator to determine size of an array. This way you won't need to define MAX. However, when passing array to a function, it looses its size information and sizeof won't work. This means you should pass size as a separate variable along with array.

Upvotes: 4

informaticienzero
informaticienzero

Reputation: 1867

It's because names[i] is of type char*, and it's exactly what printf("%s") is expecting. Using a * front of it would give a single char.

On the opposite, ptr[i] is of type int*. And that's because printf("%d") expects a single int that a * is needed front of ptr.

Upvotes: 2

Related Questions