简体   繁体   English

以struct数组指针作为参数的函数,C语言

[英]function with a struct array pointer as an argument, C language

typedef struct {
    char manufacturer[SIZE];
    char model[SIZE];
    int size;
    int id;
    int qty;
    double cost;
    double price;
} tv;    

void firstSix(tv *tvarr[]);
void firstSix(tv *tvarr[])
{
    (*tvarr[0]).manufacturer = "Vizio";
}

I am making an inventory program. 我正在制定库存程序。 It consists of an array of structs that will store information about different televisions. 它由一系列结构组成,这些结构将存储有关不同电视的信息。 In my program I am required to hardcode six entries into the array, so I am trying to make a function that will take a struct array pointer argument. 在我的程序中,我需要将六个条目硬编码到数组中,因此我试图创建一个将采用结构数组指针参数的函数。 In the above code, I included the struct declaration, the function prototype and function definition that I am trying to make. 在上面的代码中,我包含了要声明的struct声明,函数原型和函数定义。 Everything is placed before and after main in the respective order. 一切都按照各自的顺序放置在main之前和之后。 I don't understand why Visual Studio is highlighting the first parenthesis in the code inside the function definition and saying "expression must be a modifiable lvalue". 我不明白为什么Visual Studio在函数定义内的代码中突出显示第一个括号并说“表达式必须是可修改的左值”。 I don't understand what it is that I am doing wrong. 我不明白我做错了什么。 Please help. 请帮忙。

You cannot assign an array like that. 您不能分配这样的数组。 You need to do 你需要做

strcpy ((*tvarr[0]).manufacturer, "Vizio");

Make sure that you don't go out of bounds when copying the string into the array. 将字符串复制到数组时,请确保不会超出范围。

You can either check the size of the string in advance or use strncpy which will limit the maximum number of characters to be copied. 您可以预先检查字符串的大小,也可以使用strncpy来限制要复制的最大字符数。

An array is not a modifiable l-value. 数组不是可修改的L值。 So basically you cannot have it on the left hand side of an assignment. 因此,基本上您不能在作业的左侧找到它。

Or may be you also might want to define manufacture as char *manufacture and then dynamically allocate the string. 也许您也可能想将manufacture定义为char *manufacture ,然后动态分配字符串。

manufacturer = strdup ("Vizio"); //manufacturer is char *

Or depending on the length first allocate the buffer 还是根据长度先分配缓冲区

manufacturer = malloc (sizeof (char) * needed_bytes);

Whenever you dynamically allocate the buffer, whenever you have finished working with it always remember to free it free (manufacturer) . 每当您动态分配缓冲区时,每当完成使用缓冲区时,请始终记住将其free (manufacturer)

I think you want to do something like 我想你想做些类似的事情

strncpy((tvarr[0])->manufacturer, "Vizio", SIZE - 1);

Kevin has it; 凯文拥有它; you can't assign a string to a pointer, you must copy the data to the array. 您不能将字符串分配给指针,必须将数据复制到数组。 I suggest strncpy to keep from running off the end of the allocated space. 我建议使用strncpy来避免耗尽分配的空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM