0

所以用户要输入未知数量的单词,我假设每个单词的最大长度为 10;我从 realloc 中得到了作为赋值 errr 的左操作数所需的左值。我是 C 新手,我尝试了 google,但找不到有用的答案。

代码:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    #define CAPACITY 10
    #define NUM_OF_WORDS 10
    int main(void)
    {

    char *word= malloc(10*sizeof(char));
    char *w[NUM_OF_WORDS];

    int i;
    int n;

    for(i = 0 ; scanf("%s", word)==1; ++i)
    {

    if( i == NUM_OF_WORDS-1)
    w = realloc(w, (NUM_OF_WORDS*=2) * sizeof(char));

    w[i] = malloc( strlen(word)+1 * sizeof(char));
    strcpy(w[i], word);
    }

    return 0;
    }
4

3 回答 3

2
  1. NUM_OF_WORDS 是常数,不能赋值。

  2. w 不应该使用数组,应该使用 char **

  3. 在 realloc 中,您应该使用 sizeof(char *)

修改代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define CAPACITY 10
#define NUM_OF_WORDS 10

int main(void)
{

    char word[10];
    char **w = (char **) malloc(NUM_OF_WORDS * sizeof(char *));

    int i;
    int capacity = NUM_OF_WORDS;

   for(i = 0 ; scanf("%s", word)==1; ++i)
   {

       if( i == capacity -1)
           w = (char **)realloc(w, (capacity *=2) * sizeof(char *));

       w[i] = (char *)malloc( strlen(word)+1 * sizeof(char));
       strcpy(w[i], word);
   }

   // at last, release w and w's element.
   while ( --i >= 0 )
   {
        free(w[i]);
   }

   free( w );       
   return 0;
}
于 2012-04-06T02:41:04.113 回答
1

如果您希望能够使用realloc(),则需要使用分配数组wmalloc()不是在堆栈上声明它。

于 2012-04-06T02:16:28.150 回答
0
w = realloc(w, (NUM_OF_WORDS*=2) * sizeof(char));

关于错误 -

预处理后的 (NUM_OF_WORDS*=2) 为 (10 *=2)。您不能将 10*2 的乘积分配给 10。 10 是一个右值,它不能被分配任何编译器抱怨的东西。您可能的意思是 (NUM_OF_WORDS * 2)

于 2012-04-06T02:21:16.430 回答