user1938455
user1938455

Reputation:

array of pointers to strings

in a C Programming its given that we can't get the values using scanf() function to array of pointers but

int main()
{
char *names[6];
int loop;
scanf("%s",names[1]);
printftf("\n%s",names[1]);
}

it is working ,when i give the input as program ,i think it is storing the input,but it prints the output correctly as the given input.after that it gives a segmentation fault... but when i do the same in a loop for getting 6 charecters

int main()
{
 char *names[6];
 int loop;
 for(loop=0;loop<6;loop++)
 scanf("%s",names[1]);
 for(loop=0;loop<6;loop++)
 printf("\n%s",names[1]);
 }

its not working please give me the answer...

Upvotes: 4

Views: 21901

Answers (2)

K-ballo
K-ballo

Reputation: 81349

The issue is that you are not allocating any space for those names. You need to initialize each element in the array if you intend to use it with scanf.

char* names[6];
for( int i = 0; i < 6; ++i )
    names[i] = malloc( 256 * sizeof *names[i] ); // or some other max value

scanf( "%s", names[1] );

Otherwise those pointers will be pointing anywhere in your memory, and attempting to read/write those locations will eventually result in a segmentation fault.

Upvotes: 11

varevarao
varevarao

Reputation: 2186

In your code names is an array of 6 pointers to char. Now each of these pointers can store the starting point (the address of the first character) of a new string. This means you can store the starting addresses of 6 different strings in your names variable.

But when you use a loop to initialize each of these strings, you need to inform the machine HOW long each string might be, so that it can allocate a continuous block of addresses whose first address can then be stored in your pointer to refer to your string. Thus, you must allocate a certain size you think should be sufficient to store your string (eg: 256 bytes, 1 byte being 1 character). In the absence of this, the machine doesn't know where to store all the bytes of your string and throws a segmentation fault due to illegal memory access.

Thus to do this, each of your 6 pointers must be allocated some space to store a string. This will be done in your loop using malloc(). Based on @K-ballo's code:

char* names[6];
int max_length = 256; // The maximum length you expect
for( int i = 0; i < 6; ++i )
    names[i] = malloc( max_length * sizeof(char) ); // allocates max_length number of bytes

scanf( "%s", names[1] );

So now you basically have a 6 different blocks of max_length continuous char addresses that are each referred to by names[i]. When you do the scanf() it reads the bytes from standard input and puts then into these allocated bytes in memory referred to by names[1].

I had a difficult time at the start understanding all this, so just thought an elaborate explanation would help. :)

Upvotes: 5

Related Questions