0

How can i add strings to an array like this ? I have a string called "line" which reads users's input and then stores it in "var" . Var is sized [10][40] so it can store 10 strings with the size of 40 each of them (hope that this is what it does ? ) .

int main (int argc, char **argv){
    int i=0,n=0;
    char line[40];
    char var[10][40];

    while(n<10){
        gets(line);
        strcpy(var[i],line);
        printf("%s",var[i]);
        i++;
        n++;
    }
}

3 Answers 3

2

gets() is dangerous and should not be used. Use fgets() to read your input and store it in your array.

PS: fgets() comes with a newline character.It is also better to check the return value of fgets() before copying the data from line to your array.

   while(i<10){
    fgets(line,sizeof(line),stdin);
    strcpy(var[i],line);
    printf("%s",var[i]);
    i++;
    }
Sign up to request clarification or add additional context in comments.

Comments

0

First, use fgets, gets is deprecated and dangerous.

The same is also true of strcpy, use strncpy instead, it allows you to specify the number of characters to copy so that you don't copy through junk memory if your string isn't NULL-terminated.

Then you can remove n, you don't need it. So you pretty much get the same code as Gopi, but DON'T USE strcpy !!!

Comments

0

You dont need a line-buffer, write your input directly to var

while( n<10 && fgets(var[n],40,stdin)!=0 ){
    strtok(var[n],"\n"); /* remove trailing newline */
    printf("%s",var[n]);
    n++;
}

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.