-1

I would like to ask how should I make absolutly dynamic strcuture of strings. Actualy I am using dynamic array with allocation of "MAX" values

Example:

const enum { MAX_WORDS = 20, MAX_LENGHT_OF_WORD = 50 }
...
char **words
words = ( char* ) malloc ( MAX_LENGHT_OF_WORD + 1 * sizeof( char* ));
for ( i = 0; i < MAX_WORDS; i++ ) {
    words[i] = ( char* ) malloc ( MAX_LENGHT_OF_WORD + 1 *sizeof( char* ));
}

Should I do it without the constats somehow? Maybe with Linked Lists?

Thank you

Jax-p
  • 7,225
  • 4
  • 28
  • 58

1 Answers1

1

See Do I cast the result of malloc?

words = ( char* ) malloc ( MAX_LENGHT_OF_WORD + 1 * sizeof( char* ));
                           ^^^^^ Does not seem right.
        ^^^^^^^^^ Definitely wrong since type of words is char**.

You can use

words = malloc ( MAX_WORDS * sizeof( char* ));

A better and more idiomatic method would be to use:

words = malloc ( MAX_WORDS * sizeof(*words));

And then...

for ( i = 0; i < MAX_WORDS; i++ ) {
    words[i] = ( char* ) malloc ( MAX_LENGHT_OF_WORD + 1 *sizeof( char* ));
                                                          ^^^^ Wrong
}

You need sizeof(char) there. You can use

    words[i] = malloc ( MAX_LENGHT_OF_WORD + 1 * sizeof(*words[i]));

Since sizeof(char) is 1, you can simplify that to:

    words[i] = malloc ( MAX_LENGHT_OF_WORD + 1);
Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • VS2015 doesn't let me compile " malloc ( MAX_WORDS * sizeof( char* )) " but "(char*) malloc ( MAX_WORDS * sizeof( char* )) " seems ok. Even it is still now absolutly dynamical, it is limited by the "max" constant... – Jax-p Mar 02 '16 at 16:53
  • 3
    If you are compiling the file as a C++ program, then you need the explicit cast. – R Sahu Mar 02 '16 at 16:57