c - 结构指针函数中未声明的变量 c

标签 c pointers struct undeclared-identifier

我仍在学习 C,并且正在做一个练习,我必须对汽车数据库进行编程。在主函数中,我声明了一个包含 100 个指向“carinfo_t”结构的指针的数组。在函数“*createcarinfo”中,应创建一个新的 carinfo_t 实例。但我遇到的问题是“brandOfCar”变量未声明。我真的不明白为什么我会收到此消息,因为编译器应该知道该变量是结构的一部分,对吗?该结构在程序中被声明为数据类型,并且指向该结构的指针在此函数的开头初始化。

如果这个问题已经在某个地方被问过,我很抱歉。很感谢任何形式的帮助。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <limits.h>

struct carinfo_t
{ 
    char *brandOfCar;
    char *modelOfCar;
    int yearCarWasBuilt;
    float valueOfCar;
};


struct carinfo_t *createCarinfo(char *brand, char *model, int year, float 
value)
{
    struct carinfo_t *newCarInfo=(struct carinfo_t*) malloc(sizeof(struct 
carinfo_t));
    newCarInfo->brandOfCar=(char*)malloc(sizeof(char)*
(strlen(brandOfCar)+1));       

//Message:  error: 'brandOfCar' undeclared (first use in this function)

//function not finished
}


int main()
{
    struct carinfo_t *carbase[100]={};

    return 0;
}

最佳答案

这是因为您调用了传递到构造函数的变量 brand,而不是 brandOfCar。同样,您调用了模型变量 model,而不是 modelOfCar。这就是 strlen 无法编译的原因。

为了保持一致性,最好将变量命名为与结构字段相同的名称,并在适当的位置添加 const:

struct carinfo_t *createCarinfo(
    const char *brandOfCar
,   const char *modelOfCar
,   int yearCarWasBuilt
,   float valueOfCar) {
    struct carinfo_t *newCarInfo=malloc(sizeof(struct carinfo_t));
    newCarInfo->brandOfCar=malloc(strlen(brandOfCar)+1);
    ...
}

另请注意,在 C 中,您不会强制转换 malloc,也不会乘以 sizeof(char),该标准要求在所有平台上都为 1。

关于c - 结构指针函数中未声明的变量 c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45658390/

相关文章:

c - 这个功能是如何工作的?

c - C 与 scanf 中的变量赋值

c - C 中的隐式 "declaration-in-instantiation"?

Delphi:引用frame中thread的control

c - 通过指针访问结构成员

c++ - 添加到结构 vector 时出现 Stanford CS 106B 错误 — 编译器问题?

c - 在c源代码中使用dll的效率

c - 我得到 "incompatible pointer type",我不明白为什么

c++ - C++ union 内的非平凡结构构造函数

javascript - 转到 : format struct for javascript (json without keys)