简体   繁体   中英

Array Elements Overwritten with Last in C

I'm trying to create a program which takes in a set number of strings (the user is asked to put in the number of strings they will enter), once it has these strings, they are placed in an array, using dynamic memory.

The ouput would be something like this:

# of Strings: 3
Cat
Dog
Elephant 

Cat
Dog
Elephant

Heres a snippet of my code, after I have the number of strings.

sptr=malloc(sizeof(char*)*nStrings);

for(i=0;i<nStrings;i++)
{
    scanf("%s",string);
    length=strlen(string);
    sptr[i]=malloc(sizeof(char)*length);
    sptr[i]=string;
}

Where sptr is the array I'll access to output the strings. So it's an array of pointers which then point to individual strings (or other arrays of characters, if you'd prefer to think of it that way).

Lets say there are two strings. I allocate memory for two pointers, Then in the first pointer, i scan in a string, i find the length of the string, i allocate memory the size of the string and i equal the pointer to the string. This all works dandy, and if I were to put a printf() right after that last line, it will work. The problem i face is, if lets say there are 3 strings, each time through sptr[i] is assigned correctly, but then outside of that block, all of the indicies of sptr are = to the last string i put in, and I have no idea why.

If you could help me out I'd appreciate it. Thanks.

sptr=malloc(sizeof(char*)*nStrings);

for(i=0;i<nStrings;i++)
{
    scanf("%s",string);
    sptr[i]=strdup(string);
}

I assume the variable string has enough memory to keep the read strings.

The error occured because you set the pointer to point to the string variable.

You need to allocate 1 character extra for the null terminator:

sptr[i]=malloc(sizeof(char)*(length+1));

Also, you need to copy the string into the newly allocated memory:

strcpy(sptr[i], string);

There are 2 problems in your code: you don't allocate enough memory. Should be length + 1 because of the ending \\0 in a string. Secondly you should use strcpy to copy the string to your allocated memory. Lookup the strdup function that handles both.

strlen doesn't account for the zero termination, you need to add one. But mainly you need to copy the string into the memory you allocate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM