I want to create an array of strings so i can fill the entries with inputs to be executed by execv. This has to be done during runtime, making it like a normal shell, but any solution i've checked regarding the matter creates an immutable array which can't take the required inputs during runtime. So what's the notation for an Array of strings in c?
1 Answer
In your array, you will have only pointers to strings. For the actual strings, (that is: character arrays) you use malloc() to reserve memory. And as a string terminated with a null character, the array of pointers is terminated by a null pointer:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char *my_array[10]; /* Max number of strings in the array is 9, because after
the last one, there must be a terminating NULL pointer */
my_array[0] = malloc(20); /* Set the max lentght for the string to 19+0 char */
strcpy(my_array[0], "First string");
my_array[1] = malloc(20);
strcpy(my_array[1], "Second string");
/* You can allocate the memory directly in the strcpy call also */
my_array[2] = strcpy(malloc(20), "Third string");
my_array[3] = NULL; /* The NULL pointer tells, there's no more strings in the array */
/* Print out all strings in the array */
for(int i=0; i<10; i++) {
if (my_array[i] == NULL)
break;
printf("%d: %s\n", i, my_array[i]);
}
}
Of course you could reserve memory for the pointer array also with malloc, and also strictly reserve only what is needed for the individual strings.
Don't forget to free memory afterwards. Memory deserves freedom!
2 Comments
Oka
Casting the return of
malloc is unnecessary in C. Additionally, reassigning the result of strcpy is redundant in this. If you are not bothering with error checking, then perhaps my_array[k] = strcpy(malloc(N), "a string"); is the pattern you're looking for.Janne Tuukkanen
Thanks! Didn't really read what I had written. Now it's much prettier.