Reserve memory in array of strings in c


Good afternoon, I want to create in c an array of strings, where each string has 1024 characters, for this I have a variable N where it tells me the number of strings I have, I'm trying it in the following way:

char *frases[1024] = (char *) malloc(sizeof(char) * N);

But this is giving me errors.

asked by Óscar Soto 17.12.2017 в 17:12

1 answer


You're doing it the other way around.

char *frases[1024]



an array of 1024 elements, each of which is a pointer to char .

For such cases, I use a very simple trick : a% auxiliary% co:

struct frase_t {
  char texto[1024];

So declaring a array of pointers of the size that we want is very simple, and I find that easier to understand:

struct frase_t *frases[N];

Now, to use struct , it must be taken into account that each element of the array must be assigned individually:

struct frase_t {
  char texto[1024];

struct frase_t *frases[N];

for( int idx = 0; idx < N; ++idx ) {
  frases[idx] = (struct frase_t *)malloc( sizeof( struct frase_t ) );

And that's it, an array of malloc( ) pointers, each of them points to a N , which has exactly struct frase_t 1024 .

To access any phrase any, we can do

( frases[5] )->texto

or even

(char *)( frases[5] );

Since in C, the first element of a char is guaranteed that starts at the same memory location as the struct itself.

answered by 18.12.2017 в 00:18