How to create an array of strings in C?

I teach myself C from a book, and I'm trying to create a crossword puzzle. I need to create an array of strings, but you have all the problems. Also, I know little about the array ...

This is a piece of code:

char word1 [6] ="fluffy", word2[5]="small",word3[5]="bunny"; char words_array[3]; /*This is my array*/ char *first_slot = &words_array[0]; /*I've made a pointer to the first slot of words*/ words_array[0]=word1; /*(line 20)Trying to put the word 'fluffy' into the fist slot of the array*/ 

But I keep getting the message:

 crossword.c:20:16: warning: assignment makes integer from pointer without a cast [enabled by default] 

Not sure what the problem is ... I tried to find a way to create an array of strings, but no luck

Any help would be greatly appreciated

Sam

+7
source share
4 answers
 words_array[0]=word1; 

word_array[0] is char , while word1 is char * . Your character cannot contain an address.

An array of strings might look like this:

 char array[NUMBER_STRINGS][STRING_MAX_SIZE]; 

If you prefer an array of pointers to your lines:

 char *array[NUMBER_STRINGS]; 

And then:

 array[0] = word1; array[1] = word2; array[2] = word3; 

Maybe you should read this one .

+11
source

Announcement

 char words_array[3]; 

creates an array of three characters. It seems you want to declare an array of character pointers:

 char *words_array[3]; 

You have a more serious problem. Announcement

 char word1 [6] ="fluffy"; 

creates an array of six characters, but you actually say that it has seven characters. All lines have an extra character '\0' , which is used to indicate the end of the line.

Declare an array of size 7:

 char word1 [7] ="fluffy"; 

or leave the size outside, and the compiler will figure it out:

 char word1 [] ="fluffy"; 
+7
source

If you need an array of strings. There are two ways:

1. Two dimensional arrays of characters

In this case, you need to know the size of your lines in advance. It looks like this:

 // This is an array for storing 10 strings, // each of length up to 49 characters (excluding the null terminator). char arr[10][50]; 

2. Array of character pointers

It looks like this:

 // In this case you have an array of 10 character pointers // and you will have to allocate memory dynamically for each string. char *arr[10]; // This allocates a memory for 50 characters. // You'll need to allocate memory for each element of the array. arr[1] = malloc(50 *sizeof(char)); 
+5
source

You can also use malloc() to allocate memory manually:

 int N = 3; char **array = (char**) malloc((N+1)*sizeof(char*)); array[0] = "fluffy"; array[1] = "small"; array[2] = "bunny"; array[3] = 0; 

If you do not know in advance (during encoding) how many lines will be in the array and how long they will be, this is the way to go. But you will have to free the memory if it is no longer in use (calling free() ).

+4
source

All Articles