Creating a string in ANSI C is very simple, as it is simply an array of characters. However, creating an array that holds strings is a little bit more tricky. This utilises C’s malloc() library.
In order to create an array of strings, you first need two things. You need the actual array container itself, which is a pointer to a pointer of type ‘char’. You will also need a pointer to a char.
/* This is the array that currently has no set size */ char** string_array; /* Note that no size has been set yet for this */ char* string;
Now that you have these two chars, you can use malloc() to designate blocks of memory, and add some text for the first string:
string = (char *)malloc(6 * sizeof(char)); /* strcpy() places text into the string */ strcpy(string, "Hello");
Note: When allocating blocks of memory for an array of characters, you will need to know how many characters there are going to be. In this case, I have allocated 6 blocks of memory. This is to hold each letter in the string, and one more for the null terminator (‘\0′);
You then need to allocate memory for the array itself to hold a set number of elements. In this case, it will only be two elements:
*string_array = (char *)malloc(2 * sizeof(char *));
Now you can add the first string to the first element of the array (element 0):
/* Adds value of 'string' to element 0 of 'string_array' */ *string_array = string;
It is possible to then assign a new value to ‘string’, which is good if you are looping as it saves you having to create multiple strings. In this case, we want to assign a new value to ‘string’ and place it into the next element of ‘string_array’:
string = (char *)malloc(6 * sizeof(char)); /* strcpy() places text into the string */ strcpy(string, "World"); *(string_array+1) = string;
Note: I have placed the second string into element ’1′ of ‘string_array’ by placing a ‘+1′ after calling ‘string_array’. If you are using this in a loop, then you can do ‘+i’ or whatever you have named the incrementing variable.
You have now just created a very simple array of Strings in ANSI C! If we print out this code, it will look like this:
printf("%s %s", *(string_array), *(string_array+1));
Output:
Hello World
Whole code:
#include <stdio.h>
#include <stdlib.h>
int main() {
/* This is the array that currently has no set size */
char** string_array;
/* Note that no size has been set yet for this */
char* string;
string = (char *)malloc(6 * sizeof(char));
/* strcpy() places text into the string */
strcpy(string, "Hello");
*string_array = (char *)malloc(2 * sizeof(char *));
/* Adds value of 'string' to element 0 of 'string_array' */
*string_array = string;
string = (char *)malloc(6 * sizeof(char));
/* strcpy() places text into the string */
strcpy(string, "World");
*(string_array+1) = string;
printf("%s %s", *(string_array), *(string_array+1));
return 0;
}
Responses to “Create an array of Strings”
Leave a Reply