1

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

2 Answers 2

2

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.
Sign up to request clarification or add additional context in comments.

2 Comments

can u plzz explain in little more detail what do u actually mean by the line "The value of a string literal is the address of its first character. " ?
@sameersoin Consider a string "Ali". It would be stored in memory and would take up 4 bytes of memory in the read only segment (4th byte for storing '\0'). When you write "Ali" all it means is the address of the 1st byte. So char *ptr="Ali"; would assign the address of the 1st byte to ptr.
0

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.

2 Comments

for using s as character we write "printf( "s = %c\n", *s );" and for string we write "printf( "s = %s\n", s ); " .Why for printing a character we use *s and for string only s??
you are not newbie (ie you can vote), consider vote up the accepted answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.