2016-03-02 46 views
-1

我想问一下,我应该如何让绝对动态的字符串结构。 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?也许与链接列表?

谢谢

+1

不要malloc的'的sizeof(字符*)''为字[I]':'的malloc的sizeof( char)',它始终为1. –

+1

链接列表将是“绝对动态的”。一个数组受其上限限制,除非你“realloc”。 –

+0

@PaulOgilvie谢谢你的提示。我不知道realloc。我认为链表将是最好的解决方案。 – JaxCze

回答

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); 
+0

VS2015不让我编译“ malloc(MAX_WORDS * sizeof(char *))“但”(char *)malloc(MAX_WORDS * sizeof(char *))“似乎没问题。即使它现在仍然是绝对动态的,它受“最大”常量的限制... – JaxCze

+3

如果您将该文件编译为C++程序,那么您需要进行显式强制转换。 –

相关问题