0

I want to create a string array where user will give the input and data will be stored in array..I have no clue how to do that-(I read several C books) Any help ll be appreciated What I tried so far:

int choice;
    printf("enter the number of the strings: ");
    scanf("%d",&choice);
char **str=(char **)malloc(100);
    int i;



    for(i=0;i<choice;i++)
    {
        printf("enter %dth element ",i+1);
            str[i]=(char *)malloc(10);
        scanf("%s",str[i]);
    }
    printf("%s",str[0]);
3
  • 3
    You just need to read more I guess, this is very basic and basic skills will enable you to do it. Commented Sep 13, 2011 at 2:14
  • yes it should! but problem is that program is terminating ! Commented Sep 13, 2011 at 2:16
  • 2
    I should hope it terminates! I'd hate to run a program that I expect to terminate and it just goes on forever. Commented Sep 13, 2011 at 2:17

3 Answers 3

1
You will have to allocate and initialize space for each string before reading them in. If you know he length of your input string then malloc/calloc that much space else guess a size but that would be wastage of space.

for(i=0;i<choice;i++)
     {
         printf("enter %dth element ",i+1);
         str[i] = malloc(sizeof(char)*length);
         memset(str[i],0,length);
         scanf("%s",str[i]);
     }  
Sign up to request clarification or add additional context in comments.

3 Comments

Yeah dynamic allocation is the way to go. But usually when you are doing input like this you do not know the size of the string, so some large buffer is used, copied, and flushed.
str[i] = malloc(sizeof(char)*length); this line does not work!
you will have to specify the "length" ...but what Jonathan suggests is the way to go.
1

You are not allocating any spaces for the strings. If you are ok with bounded arrays you could define str as char str[100][128] to have 100 strings up to 128 chars each. At least until you learn some basic dynamic allocation.

1 Comment

i know dynamic allocation-I can do that
0

If I am reading this correctly, you have defined a pointer to an array of 100 chars. What you really want is 'choice' arrays of length 100 of chars I think char str[choice][100]

and then you can use your array as you have for the reading and printing of string input.

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.