-2

I create a big 2d char array and want to assign strings to it.

int i;
char **word;
int start_size = 35000;
word=(char **) malloc(start_size*sizeof(char *));
for(i=0;i<start_size;i++)
    word[i]=(char *) malloc(start_size*sizeof(char));

word[2][2] = "word";

how do I assign a string? Explain me why this code doesn't work... I am new to low level programming and C but experienced in high level programming

3 Answers3

0

You cannot do string assignment in C.

You need to call a function, sepcifically strcpy() (prototype in <string.h>)

#include <string.h>

strcpy(word[2], "word");
pmg
  • 106,608
  • 13
  • 126
  • 198
0

You have to decide if you want a list of strings or a 2D array of strings.


A list of string works like this:

char **word;
word = (char**)malloc(start_size*sizeof(char*));
word[2] = "word";

In this example word[2] would be the third string in the list and word[2][1] would be the second character in the third string.


If you want a 2D array of string you have to do this:

int i;
char ***word;
     ^^^ 3 stars
int start_size = 35000;
word = (char***)malloc(start_size*sizeof(char**));
            ^^^ 3 stars                        ^^^ 2 stars
for(i=0;i<start_size;i++)
    word[i] = (char**) malloc(start_size*sizeof(char*));
                   ^^^ 2 stars                     ^^^ 1 star

word[2][2] = "word"; // no it works!

Note that in C you do not need the casts before the malloc. So this would also work:

word = malloc(start_size*sizeof(char**));
Danvil
  • 22,240
  • 19
  • 65
  • 88
0
word[2][2] = "word";

In the above statement, the string literal "word" is implicitly converted to a pointer to its first element which has type char * whereas word[2][2] has type char. This attempts to assign a pointer to a character. This explains the warning message you have stated -

assignment makes integer from pointer without a cast

You can use string literals only to initialize character arrays. What you need to do is use the standard function strcpy to copy the string literal. Also, you should not cast the result of malloc. Please read this - Do I cast the result of malloc? I suggest the following changes -

int i;
int start_size = 35000;

// do not cast the result of malloc
char **word = malloc(start_size * sizeof *word);

// check word for NULL in case malloc fails 
// to allocate memory

for(i = 0; i < start_size; i++) {
    // do not cast the result of malloc. Also, the
    // the sizeof(char) is always 1, so you don't need
    // to specify it, just the number of characters 
    word[i] = malloc(start_size);

    // check word[i] for NULL in case malloc
    // malloc fails to allocate memory
}

// copy the string literal "word" to the 
// buffer pointed to by word[2]
strcpy(word[2], "word");
Community
  • 1
  • 1
ajay
  • 9,402
  • 8
  • 44
  • 71