简体   繁体   中英

how can an array of pointers to char hold strings instead of addresses?

Can anyone explain how the following program works? here name[] is an array of pointers to char then how can name contain values instead of addresses and how come the values stored are strings rather than character?

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

A string literal like "Zara Ali" evaluates to the address of its first character.

The string literal is generally stored in read-only data segment.

So essentially your array contains addresses .

You can also write

char *str="Zara Ali";
//The value of a string literal is the address of its first character.

You can take a simpler example:

char *s = "abcd";
printf( "s = %p\n", (void *)s );  // 1) address
printf( "s = %c\n", *s );         // 2) char
printf( "s = %s\n", s );          // 3) string

Here s is a pointer to char (similar to your names[i] , also a pointer to char). Actually s can be interpreted as 1) an address, 2) a normal pointer to char, or 3) a string.

First s is a pointer, so s holds address of something it points to. You can check what address it is by the first printf using %p control string.

Second, s is a pointer to char, so you can deference it as normal, using printf %c which would print the first char.

Third, s is a pointer to char which is one way to declare C string (another way is using array). C string is a consecutive array of characters ending with \\0 as delimiter. When using printf %s you are printing it as a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM