2 ways to access the value of an array of pointers in C

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;
}

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

Now the second block is exactly the same, but now it points to a pointer array char:

#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;
}

This time, when we need to access its element, why not add it first *?

I tried to generate the correct instruction for printing this value, it seems if you dereferenced, it will be one char. Why?

printf("%c", *names[1]) // Z

I know that in C there are no lines, and this is an array char. And I know pointers, but still not under the syntax.

+4
4

printf() %s, C11, §7.21.6.1

s
l, . [...]

 printf("Value of names[%d] = %s\n", i, names[i] );

names[i] , %s. .

FWIW,

  • %c int ( unsigned char,), , .
  • %d int, , .
+2

%d , int; ptr[i] int *, .

%s , char *; char. , names[i] . %s printf , , , .

+1

, char:

    printf("Value of names[%d] = %c\n", i, *names[i]);

C, names, , char *.

0

printf()has its own way of working with type specifiers. In the case of strings, that is, an array of characters, this requires a qualifier %sand a type pointer char *as the corresponding argument. When it printf()receives this pointer, it searches for it unnoticed by type characters char. So, that’s why you pass the pointer and don't play when you want to print lines.

0
source

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


All Articles