I am trying to add a string to an array, but I'm not sure how come this code isn't working. Would anyone please be able to leave me some feedback?
/* Exercise b: Add <string> to the end of array <array>.
* Returns: pointer to the array after the string has been added.
*/
char **add_string(char **array, const char *string) {
/*reallocate so the array of strings can hold one more string*/
char** newArray = realloc(array, sizeof (array) + sizeof (char*));
if (!newArray) return array;
/*allocate memory for new string*/
char* newString = malloc(strlen(string) * sizeof (char));
if (!newString) return newArray;
/*copy old string to new string*/
int lastIndex = sizeof (newArray) / sizeof (char*);
strncpy(newString,string,strlen(string));
/*null terminate array and set old end of array to new string*/
newArray[lastIndex] = NULL;
newArray[lastIndex-1] = newString;
return newArray;
}
When I run the code, the core dumps, but I dont see why
The reason why I am asking is because I am aware that it would be easy to pass in the size of the array. But for this method, I am not allowed. Unfortunatley, my professor does says that the fuction parameters must stay the same
sizeof(array)andlastIndexand seeing if they're taking the values you expect.sizeof (newArray)that does not do what you want.sizeofon a pointer gives the pointer size not the array size (because it is not actually a C array - pointers and arrays are different in C even though they behave similar in many cases).NULL, you have to loop through the array until you findNULL, and count the elements. Then you can add 1 to that and multiply bysizeof(char*)malloc(strlen(string))is pretty much always wrong.