I'm struggling to see how I can append a string to an array of strings, given that the value being added to each time (therefore the value the pointer points to is changing). I'm expecting array
to be in the format {"hello, "helloo", ...}
but I can't get this to work. What changes can I make so that array
stores this correctly?
int size = 10;
char *string = "hello";
char c = "o";
char *array[size];
for (int i = 0; i < 10; i ) {
strcat(string, c);
array[i] = string;
}
CodePudding user response:
Oops... there are tons of errors here!
Let us go back to the basics: C language has no notion of what a string could be. At the language level you only have the (single) character type: char
. At the library level, a string is representented by a null terminated character array.
So to be able to add a character to a string, you must have an array of the correct dimension. BTW, a litteral like "hello"
is a const character array: the programmer cannot change anything to it.
So here you want to be able to add 1 to 10 character to "hello", so you need a 16 character array: 5 for hello, 10 for the additional o
and 1 for the null. But that is not all, array
is just an array of pointers. If all elements of array
point to the same string to which you add characters, at the end they will all have the very same value! You must have each element of the array to point to a different character array. Assuming that strdup
is available you could write:
int size = 10;
char string[16] = "hello"; // build an array of size 16 initialized to "hello"
const char *c = "o"; // beware a string literal IS const
char *array[size];
for (int i = 0; i < 10; i ) {
strcat(string, c);
array[i] = strdup(string); // build a dynamic copy
}
When you will no longer need array
you should free all strings allocated with strdup
:
for (int i = 0; i < 10; i ) {
free(array[i]);
}
BTW, strdup
is only in the standard C library since C23, it previously was just a POSIX extension. If is in not available on your system you can roll you own:
char *strdup(const char *src) {
char *dest = malloc(1 strlen(src));
strcpy(dest, src);
return dest;
}
Alternatively you could avoid dynamic allocation by using a true 2D array:
int size = 10;
char string[16] = "hello"; // build an array of size 16 initialized to "hello"
const char *c = "o"; // beware a string literal IS const
char *array[size][16]; // this is an array of 10 strings of size 16
for (int i = 0; i < 10; i ) {
strcat(string, c);
strcpy(array[i], string);
}
CodePudding user response:
Unless the string is dynamically allocated, the size needs to be pre determined. Also, char str_name[size]
is how a string is defined.
int size = 10;
char string[size 5] = "hello";
char c[2] = "o";
char* array[size];
for (int i = 0; i < size; i ) {
array[i] = string;
strcat(string, c);
}