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