How do I create an array of strings in C?

CArraysString

C Problem Overview


I am trying to create an array of strings in C. If I use this code:

char (*a[2])[14];
a[0]="blah";
a[1]="hmm";

gcc gives me "warning: assignment from incompatible pointer type". What is the correct way to do this?

edit: I am curious why this should give a compiler warning since if I do printf(a[1]);, it correctly prints "hmm".

C Solutions


Solution 1 - C

If you don't want to change the strings, then you could simply do

const char *a[2];
a[0] = "blah";
a[1] = "hmm";

When you do it like this you will allocate an array of two pointers to const char. These pointers will then be set to the addresses of the static strings "blah" and "hmm".

If you do want to be able to change the actual string content, the you have to do something like

char a[2][14];
strcpy(a[0], "blah");
strcpy(a[1], "hmm");

This will allocate two consecutive arrays of 14 chars each, after which the content of the static strings will be copied into them.

Solution 2 - C

There are several ways to create an array of strings in C. If all the strings are going to be the same length (or at least have the same maximum length), you simply declare a 2-d array of char and assign as necessary:

char strs[NUMBER_OF_STRINGS][STRING_LENGTH+1];
...
strcpy(strs[0], aString); // where aString is either an array or pointer to char
strcpy(strs[1], "foo");

You can add a list of initializers as well:

char strs[NUMBER_OF_STRINGS][STRING_LENGTH+1] = {"foo", "bar", "bletch", ...};

This assumes the size and number of strings in the initializer match up with your array dimensions. In this case, the contents of each string literal (which is itself a zero-terminated array of char) are copied to the memory allocated to strs. The problem with this approach is the possibility of internal fragmentation; if you have 99 strings that are 5 characters or less, but 1 string that's 20 characters long, 99 strings are going to have at least 15 unused characters; that's a waste of space.

Instead of using a 2-d array of char, you can store a 1-d array of pointers to char:

char *strs[NUMBER_OF_STRINGS];

Note that in this case, you've only allocated memory to hold the pointers to the strings; the memory for the strings themselves must be allocated elsewhere (either as static arrays or by using malloc() or calloc()). You can use the initializer list like the earlier example:

char *strs[NUMBER_OF_STRINGS] = {"foo", "bar", "bletch", ...};

Instead of copying the contents of the string constants, you're simply storing the pointers to them. Note that string constants may not be writable; you can reassign the pointer, like so:

strs[i] = "bar";
strs[i] = "foo"; 

But you may not be able to change the string's contents; i.e.,

strs[i] = "bar";
strcpy(strs[i], "foo");

may not be allowed.

You can use malloc() to dynamically allocate the buffer for each string and copy to that buffer:

strs[i] = malloc(strlen("foo") + 1);
strcpy(strs[i], "foo");

BTW,

char (*a[2])[14];

Declares a as a 2-element array of pointers to 14-element arrays of char.

Solution 3 - C

Ack! Constant strings:

const char *strings[] = {"one","two","three"};

If I remember correctly.

Oh, and you want to use strcpy for assignment, not the = operator. strcpy_s is safer, but it's neither in C89 nor in C99 standards.

char arr[MAX_NUMBER_STRINGS][MAX_STRING_SIZE]; 
strcpy(arr[0], "blah");

Update: Thomas says strlcpy is the way to go.

Solution 4 - C

Here are some of your options:

char a1[][14] = { "blah", "hmm" };
char* a2[] = { "blah", "hmm" };
char (*a3[])[] = { &"blah", &"hmm" };  // only since you brought up the syntax -

printf(a1[0]); // prints blah
printf(a2[0]); // prints blah
printf(*a3[0]); // prints blah

The advantage of a2 is that you can then do the following with string literals

a2[0] = "hmm";
a2[1] = "blah";

And for a3 you may do the following:

a3[0] = &"hmm";
a3[1] = &"blah";

For a1 you will have to use strcpy() (better yet strncpy()) even when assigning string literals. The reason is that a2, and a3 are arrays of pointers and you can make their elements (i.e. pointers) point to any storage, whereas a1 is an array of 'array of chars' and so each element is an array that "owns" its own storage (which means it gets destroyed when it goes out of scope) - you can only copy stuff into its storage.

This also brings us to the disadvantage of using a2 and a3 - since they point to static storage (where string literals are stored) the contents of which cannot be reliably changed (viz. undefined behavior), if you want to assign non-string literals to the elements of a2 or a3 - you will first have to dynamically allocate enough memory and then have their elements point to this memory, and then copy the characters into it - and then you have to be sure to deallocate the memory when done.

Bah - I miss C++ already ;)

p.s. Let me know if you need examples.

Solution 5 - C

Or you can declare a struct type, that contains a character arry(1 string), them create an array of the structs and thus a multi-element array

typedef struct name
{
   char name[100]; // 100 character array
}name;

main()
{
   name yourString[10]; // 10 strings
   printf("Enter something\n:);
   scanf("%s",yourString[0].name);
   scanf("%s",yourString[1].name);
   // maybe put a for loop and a few print ststements to simplify code
   // this is just for example 
 }

One of the advantages of this over any other method is that this allows you to scan directly into the string without having to use strcpy;

Solution 6 - C

If the strings are static, you're best off with:

const char *my_array[] = {"eenie","meenie","miney"};

While not part of basic ANSI C, chances are your environment supports the syntax. These strings are immutable (read-only), and thus in many environments use less overhead than dynamically building a string array.

For example in small micro-controller projects, this syntax uses program memory rather than (usually) more precious ram memory. AVR-C is an example environment supporting this syntax, but so do most of the other ones.

Solution 7 - C

If you don't want to keep track of number of strings in array and want to iterate over them, just add NULL string in the end:

char *strings[]={ "one", "two", "three", NULL };

int i=0;
while(strings[i]) {
  printf("%s\n", strings[i]);
  //do something
  i++;
};

Solution 8 - C

In ANSI C:

char* strings[3];
strings[0] = "foo";
strings[1] = "bar";
strings[2] = "baz";

Solution 9 - C

The string literals are const char *s.

And your use of parenthesis is odd. You probably mean

const char *a[2] = {"blah", "hmm"};

which declares an array of two pointers to constant characters, and initializes them to point at two hardcoded string constants.

Solution 10 - C

Your code is creating an array of function pointers. Try

char* a[size];

or

char a[size1][size2];

instead.

See wikibooks to arrays and pointers

Solution 11 - C

hello you can try this bellow :

 char arr[nb_of_string][max_string_length]; 
 strcpy(arr[0], "word");

a nice example of using, array of strings in c if you want it

#include <stdio.h>
#include <string.h>


int main(int argc, char *argv[]){

int i, j, k;

// to set you array
//const arr[nb_of_string][max_string_length]
char array[3][100];

char temp[100];
char word[100];

for (i = 0; i < 3; i++){
	printf("type word %d : ",i+1);
	scanf("%s", word);
	strcpy(array[i], word);
}

for (k=0; k<3-1; k++){
	for (i=0; i<3-1; i++)
	{
		for (j=0; j<strlen(array[i]); j++)
		{
			// if a letter ascii code is bigger we swap values
			if (array[i][j] > array[i+1][j])
			{
				strcpy(temp, array[i+1]);
				strcpy(array[i+1], array[i]);
				strcpy(array[i], temp);

				j = 999;
			}

			// if a letter ascii code is smaller we stop
			if (array[i][j] < array[i+1][j])
			{
        			j = 999;
			}

		}
	}
}

for (i=0; i<3; i++)
{
	printf("%s\n",array[i]);
}

return 0;
}

Solution 12 - C

char name[10][10]
int i,j,n;//here "n" is number of enteries
printf("\nEnter size of array = ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
    for(j=0;j<1;j++)
    {
        printf("\nEnter name = ");
        scanf("%s",&name[i]);
    }
}
//printing the data
for(i=0;i<n;i++)
{
    for(j=0;j<1;j++)
    {
        printf("%d\t|\t%s\t|\t%s",rollno[i][j],name[i],sex[i]);
    }
    printf("\n");
}

Here try this!!!

Solution 13 - C

I was missing somehow more dynamic array of strings, where amount of strings could be varied depending on run-time selection, but otherwise strings should be fixed.

I've ended up of coding code snippet like this:

#define INIT_STRING_ARRAY(...)          \
    {                                   \
        char* args[] = __VA_ARGS__;     \
        ev = args;                      \
        count = _countof(args);         \
    }

void InitEnumIfAny(String& key, CMFCPropertyGridProperty* item)
{
    USES_CONVERSION;
    char** ev = nullptr;
    int count = 0;

    if( key.Compare("horizontal_alignment") )
        INIT_STRING_ARRAY( { "top", "bottom" } )

    if (key.Compare("boolean"))
        INIT_STRING_ARRAY( { "yes", "no" } )

    if( ev == nullptr )
        return;

    for( int i = 0; i < count; i++)
        item->AddOption(A2T(ev[i]));

    item->AllowEdit(FALSE);
}

char** ev picks up pointer to array strings, and count picks up amount of strings using _countof function. (Similar to sizeof(arr) / sizeof(arr[0])).

And there is extra Ansi to unicode conversion using A2T macro, but that might be optional for your case.

Solution 14 - C

Each element is a pointer to its first character

const char *a[2] = {"blah", "hmm"};

Solution 15 - C

A good way is to define a string your self.

#include <stdio.h>
typedef char string[]
int main() {
    string test = "string";
    return 0;
}

It's really that simple.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCharlesView Question on Stackoverflow
Solution 1 - CMikael AunoView Answer on Stackoverflow
Solution 2 - CJohn BodeView Answer on Stackoverflow
Solution 3 - CmpenView Answer on Stackoverflow
Solution 4 - CFaisal ValiView Answer on Stackoverflow
Solution 5 - CFutureSciView Answer on Stackoverflow
Solution 6 - CBryceView Answer on Stackoverflow
Solution 7 - CSergeyView Answer on Stackoverflow
Solution 8 - CNoldorinView Answer on Stackoverflow
Solution 9 - Cdmckee --- ex-moderator kittenView Answer on Stackoverflow
Solution 10 - CDarioView Answer on Stackoverflow
Solution 11 - CAominéView Answer on Stackoverflow
Solution 12 - CAdityaView Answer on Stackoverflow
Solution 13 - CTarmoPikaroView Answer on Stackoverflow
Solution 14 - CashkanyoView Answer on Stackoverflow
Solution 15 - CIceCodrView Answer on Stackoverflow