2 ways of accessing value of an array of pointers in C

Alb*_*Gao 7 c arrays printf pointers format-specifiers

The first block

#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;
}
Run Code Online (Sandbox Code Playgroud)

Easy to understand, since ptr is an array of int pointers. So when you need to access the i-th element, you need to dereference its value as *ptr[i].

Now the second block, just the same, but now it points to an array of char pointer:

#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;
}
Run Code Online (Sandbox Code Playgroud)

This time, when we need to access its element, why don't we add a * first?

I tried to form a correct statement to print this value, seems if you dereference, it will be a single char. Why?

printf("%c", *names[1]) // Z
Run Code Online (Sandbox Code Playgroud)

I know there is no strings in C, and it is a char array. And I know pointers, but still don't under the syntax here.

Sou*_*osh 4

For printf() with %s format specifier, quoting C11, chapter \xc2\xa77.21.6.1

\n\n
\n

s
If no l length modifier is present, the argument shall be a pointer to the initial\n element of an array of character type. [...]

\n
\n\n

In your case,

\n\n
 printf("Value of names[%d] = %s\\n", i, names[i] );\n
Run Code Online (Sandbox Code Playgroud)\n\n

names[i] 指针,根据 的要求%s。这就是为什么,你不取消引用指针。

\n\n

FWIW,

\n\n
    \n
  • %c期望一个int type argument (converted to an\nunsigned char,), so you need to dereference the pointer to get the value.
  • \n
  • %d还期望一个int argument, so you have to go ahead and dereference the pointer, as mentioned in the question.
  • \n
\n