我想问一下如何制作绝对动态的弦乐结构。 Actualy我使用动态数组分配“MAX”值
示例:
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* ));
}
我是否应该以某种方式在没有constats的情况下这样做?也许与链接列表?
谢谢
答案 0 :(得分:1)
请参阅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**.
您可以使用
words = malloc ( MAX_WORDS * sizeof( char* ));
更好,更惯用的方法是使用:
words = malloc ( MAX_WORDS * sizeof(*words));
然后......
for ( i = 0; i < MAX_WORDS; i++ ) {
words[i] = ( char* ) malloc ( MAX_LENGHT_OF_WORD + 1 *sizeof( char* ));
^^^^ Wrong
}
你需要sizeof(char)
。你可以使用
words[i] = malloc ( MAX_LENGHT_OF_WORD + 1 * sizeof(*words[i]));
由于sizeof(char)
为1
,您可以将其简化为:
words[i] = malloc ( MAX_LENGHT_OF_WORD + 1);