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;
}
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;
}
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
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.
%stellsprintfto print all the characters starting at the given address, and until encountering 0. In your example, the given address is the value ofnames[i]. The%ctellsprintfto print the given character.In your example, the given character is the value of*names[i], which is equivalent tonames[i][0].