c - 表达式必须是可修改的左值(指向结构的指针)

标签 c arrays pointers struct structure

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

在我的程序中,我有一个函数 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[] 是一个指向从程序中其他地方传递的结构的指针数组)。

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

这是我的结构定义,以防需要:

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

这个程序是为了类作业,所以虽然我感谢任何帮助的努力,但我只关心如何能够在 tempptr 中存储值,以便我可以执行交换。谢谢。

最佳答案

您需要使用:

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

您无法分配 char[50] 数组,您必须复制到它。

关于c - 表达式必须是可修改的左值(指向结构的指针),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30314013/

相关文章:

c - 将 for 循环中的每个结果作为表格打印出来,并显示每次迭代和结果

c - 如何强制 C 程序在特定内核上运行

c - strcpy 和 strcat 的垃圾

javascript - 在 DOM 上显示我的代码时遇到问题

c - 将整数类型转换为指针时出现整数指针赋值故障

c - C 中带有指向其他结构数组指针的结构的问题

C编程-3 if语句中的测试条件

php - 使用 PHP 进行 MySQL 查询的 JSONArray 不适用于复杂的查询

C++ 入门加 : 2D Arrays

c - 如果类型与左侧操作数匹配,为什么要显式转换右侧指针操作数?