1

我为 r 分配了内存,它是一个指向 struct 的双指针。然而,当我试图使用这个变量时,我得到了一个错误,它说:

错误信息

read-command.c:461:7: error: lvalue required as left operand of assignment
   r+i = postfixToTree(postfix_string, &csPtr->nodeArray[i]);
       ^
make: *** [read-command.o] Error 1

用法

r+i = postfixToTree(postfix_string, &csPtr->nodeArray[i]);

宣言

宣言

   int b;
    struct command** r;
    r = (struct command**) malloc(50 * sizeof(struct command*));
    for( b=0; b<50; b++){
      *(r+b)=(struct command*) malloc(50*sizeof(struct command));
    }

如何为 r 赋值?

4

3 回答 3

2

C 赋值的一般语法。

    Lvalue=Rvalue;

上面的 Rvalue 可以是表达式或函数调用的结果,或者只是另一个相同类型或常量的变量,Lvalue 是可以存储 Rvalue 的变量。

r+i = postfixToTree(postfix_string, &csPtr->nodeArray[i]);  

^^^   

试图将 i 值添加到 r ,而不是Lvalue

在 C 中,左侧不应有任何评估部分。

先加后赋值

  r=r+i; //r+=i; 
  r = postfixToTree(postfix_string, &csPtr->nodeArray[i]);     

你可以写上面的语句如下

  r[i] = postfixToTree(postfix_string, &csPtr->nodeArray[i]);     

每次调用函数时postfixToTree()

for( b=0; b<50; b++)
  *(r+b)=(struct command*) malloc(50*sizeof(struct command));

在这里,您正在创建on的50副本。这样做会泄漏大量内存。struct commandeach iteration

还有内部函数free()分配的内存。malloc()

于 2013-10-08T02:56:07.827 回答
1

这是你想要的吗?确保包括stdlib.h,不需要 malloc 强制转换,*(r+b)它相当于r[b].

#include <stdlib.h>

struct command {
    int x; // just a definition to compile
};

int main()
{
    int b;
    struct command** r;
    r = malloc(50 * sizeof(struct command*));
    for( b=0; b<50; b++) {
        r[b] = malloc(50*sizeof(struct command));
    }
}
于 2013-10-08T03:58:38.357 回答
0

我认为你对指针做错了。

这样做,

 int b;
    struct command** r;
    r = (struct command**) malloc(50 * sizeof(struct command*));
    for( b=0; b<50; b++){
      *(r) + b=(struct command*) malloc(50*sizeof(struct command));
    }
于 2013-10-08T03:51:27.877 回答