【问题标题】:Expression must be a modifiable lvalue (pointer to struct)表达式必须是可修改的左值(指向结构的指针)
【发布时间】:2015-05-18 22:51:06
【问题描述】:

我看过类似的问题,但还没有真正找到我的问题的答案。

在我的程序中,我有一个函数,sortdata,如下:

void sortdata(Person *arr[], int noElements)
{
    /* temporary pointer to Person data type to aid with swapping */
    Person *tempptr = (Person *)malloc(sizeof(Person));

    int i = 0;

    /* loop I am working on to sort my data */
    if (arr[i]->zip > arr[i + 1]->zip) 
    {
        /* stores value in index i for array inside of temporary pointer */
        tempptr->name = arr[i]->name;
    }
}

我在这一行收到问题中描述的错误:

  tempptr->name = arr[i]->name;

temp 不被识别为可修改的左值。为什么是这样?我在程序的另一个函数中有这段代码:

while ((gets(teststring)) != NULL && i < 50)
{
    /* dynamically allocates memory for each index of the array */
    arr[i] = (Person*)malloc(sizeof(Person));

    /* takes in data from user/ input file */

    strcpy(arr[i]->name, teststring);
    gets(arr[i]->address);
    gets(arr[i]->citystate);
    gets(arr[i]->zip);
    printf("\n");
}

我之前没有初始化 arr[](arr[] 是一个指针数组,指向从程序中其他地方传递的结构)。

如何才能将值存储在 tempptr 中的 arr[i] 中?

这是我的结构定义,以备不时之需:

/* structure defintion with typedef */
typedef struct person{
    char name[50];
    char address[50];
    char citystate[30];
    char zip[10];
}Person;

这个程序是用于课堂作业的,所以虽然我很感激任何帮助,但我只关心如何能够将值存储在 tempptr 中,以便我可以执行交换。谢谢。

【问题讨论】:

    标签: c arrays pointers struct structure


    【解决方案1】:

    你需要使用:

    strcpy(tempptr->name, arr[i]->name);
    

    您不能分配 char[50] 数组,而必须复制到它。

    【讨论】:

    • 这修复了它!谢谢!为什么我不能做我想做的事?
    • @MV94 在 C 中,您不能分配给数组。所以:char s[40]; 后跟 s = "foo"; 是一个错误。但是你可以复制到一个数组:strcpy(s, "foo");.
    • 啊。所以它给了我一个错误,因为我试图修改的成员是一个数组,我给它分配了一个字符串值。谢谢,我明白了。
    【解决方案2】:

    你需要使用strcpy来修改char[]。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 2013-02-09
      相关资源
      最近更新 更多