0

When we are using a 2-D array of characters we are at liberty to either initialize the strings where we are declaring the array,or receive the string using scanf() fucntion.However when we are using an array of pointers we can not receive the strings from keyboard using scanf(). why?

#include<stdio.h>

int main()
{
char *names[6];
int i;
for(i=0;i<=5;i++)
{

    printf("Enter name:");
    scanf("%s",names[i]);

}
return 0;
2
  • 2
    Because the pointers don't point to anywhere you can write to? Commented Oct 4, 2014 at 8:54
  • 1
    Also this is not a 2D array of characters. Look up the basics about the difference between pointers and arrays in C. Commented Oct 4, 2014 at 9:17

3 Answers 3

4

Your code doesn't work because it invokes undefined behavior by storing strings into pointers which are not initialized to point to anything. You need to use malloc().

valgrind is a tool which would catch this sort of program for you, automatically.

Sign up to request clarification or add additional context in comments.

Comments

3
 char *names[6];  

declares names as an array of pointers to char but does not allocate memory for elements of names. You need to allocate memory for each element before writing to it, otherwise it will invoke undefined behavior.

Try this:

for(i = 0; i <= 5; i++)
{
     printf("Enter name:");
     names[i] = malloc(SIZE);  // SIZE is for length of string
     if( names[i] != NULL)
         scanf("%s", names[i]);
}

2 Comments

@Down Voter; A comment would be appreciated.
Not the downvoter, but perhaps it was due to your use of gets (spelled slightly differently), or failure to check return value of malloc
2

scanf does not allocate memory automatically, so you have to allocate a buffer for storing the input before calling scanf.

#include<stdio.h>

int main()
{
char *names[6];
int i;
for(i=0;i<=5;i++)
{
printf("Enter name:");
names[i]=(char *)malloc(256); // 256 is size of buffer
scanf("%s",names[i]);

}
return 0;

Comments

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.