Array Elements Overwritten with Last in C -


I am trying to create a program that takes a fixed number of strings (to put the user in number They are called for strings they will enter), once after these strings, they are placed in an array using dynamic memory.

The output will be something like this:

  # of strings: 3 cat dog elephant cat dog elephant  

after the number of my strings My code has a snippet.

  sptr = malloc (sizeof (four *) * nStrings); (I = 0; i & lt; nStrings; i ++) for {scanf ("% s", string); Length = strlen (string); Sptr [i] = malloc (sizeof (four) * length); Sptr [i] = string; }  

When I have a sptr array, I will use the string to output. So this is an array, which then indicates individual strings (or other arrays of letters, if you would like to think it like this).

We say that there are two strings. I assign memory to two points, then in the first indicator, I scan in a string, I get the length of the string, I assign the size of the memory string and I am equal to the pointer for the string. It all works, and if I put a printf () after the last line, then it will work. The problem I give, if we say that there are 3 strings, then each time is correctly allocated through the spt [i], but then put all indicies in the outside of that block into the final string I and I do not know why.

If you can help me, then I appreciate it. Thank you.

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

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

In addition, you need to copy the string in the new allocated memory:

  strcpy (sptr [i], string);  

Comments

Popular posts from this blog

oracle - The fastest way to check if some records in a database table? -

php - multilevel menu with multilevel array -

jQuery UI: Datepicker month format -