I have the following code to populate an array of strings, but every time i change the value, the entire array changes (instead of a single string the array)
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
That’s because you are the same pointer to char for all positions of the array.
When you do:
You are assigning a pointer. So every single
word[i]is the same string (txt).If you really want to read the word into a buffer (like
txt) and then put it into the array of strings, you need to copy the contents of the buffer string to the string in the array, like so:There’s also another problem with your code, which is the allocation of the string array.
It should be:
That is because a string array is a pointer to a char pointer (
char**), and each element of the array is a string (char*). Now you have allocated a array of char pointers, but you have not allocated the memory for each string, which is what we do next:If you want to not use a buffer and read directly into the string array, your code would be something like this: