Issue
Let's say I have an empty array that will be filled with strings, how do I then append a string to it when I want to?
Here is what I kind of have so far
string people[20] = {};
string name = "james";
strcpy(people[0], name);
Solution
Taking into account your code snippet
string people[20] = {};
string name = "james";
strcpy(people[0], name);
it seems that the type string
is defined like
typedef char * string;
So this declaration
string people[20] = {};
declares an array of elements of the type char *
.
You may not use as an initializer empty braces. You need to write at least like
string people[20] = { NULL };
So to add an element to the array you should write
people[0] = name;
Or without using an intermediate variable
people[0] = "james";
Another approach is to allocate a memory dynamically for an element of the array and copy in the memory a string. For example
people[0] = malloc( strlen( name ) + 1 );
strcpy( people[0], name );
Answered By - Vlad from Moscow Answer Checked By - Terry (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.