Note that I'm converting from a string to a char** |
No, you're converting a
string to a
char*. There's a difference. You're then storing that char* in an array, for some reason. But, even once you get this right,
name isn't a string, it's an array of strings.
The point is that
name is an array of pointers. A pointer is just a number, and that number is a memory address. But just because you have a memory address, doesn't mean that you can just write data to that address, because for all you know that memory is being used for something important, if you're lucky.
In your code, not only have you not allocated memory, you haven't even given the char* pointer in the array any value it all. The value is completely random.
In your code, at line 8, you're setting the value of
name[0] to be the pointer returned by
food.c_str(). However, that points to memory managed by
food; when food is destroyed, that memory is freed up, so
name[0] now points to invalid memory.
You need to make sure name[0] points to memory that's going to persist after the function exits. Which means you need to allocate that memory yourself.
EDIT: If the things I'm saying don't make any sense to you, then I suspect it's because you've never really learned about pointers, or about memory allocation. In which case, the best thing you can do is go back to your textbook and read those chapters.