I was coding a function that receives a string, updates it, and then returns the same string, but with some changes. When I try copying that string in order to change it as an array, I'm getting the error message "array initializer must be an initializer list or string literal". Here's where I get the error:
string replace(string word)
{
char updated[] = word; // The error points out this line
}
>>> // error: array initializer must be an initializer list or string literal
// char updated[] = word;
^
I'm trying to create an array of characters, in order to form a string, from a string literal. However, it doesn't seem to work. For now, I just want to understand better how an array of characters work and why this won't work. Thanks in advance!
CodePudding user response:
You need to strcpy/memcpy from word to updated, but you also need to allocate memory (malloc) for updated.
What you return shouldn't be a string, which is a typedef for char* that cs50 automatically releases (via an atexit callback) when the program exits, because your manual allocation will not be automatically free'd. You should return a char* that you later free.
CodePudding user response:
char updated[] = word; is invalid in C as C language does not have constructors.
You need to:
char updated[strlen(word) 1];
strcpy(updated, word);
