如何在c语言中使用结构体
How to use struct in c?
下面是我的代码:
struct Point
{
int i;
int j;
};
int main(int argc, char *argv[])
{
int n = atoi(argv[1]);
int a;
int b;
for(a = 0; a < n; a++)
{
for(b = a+1; b < n; b++)
{
struct Point *data = (struct Point *) malloc(sizeof(struct Point));
data.i = a;
data.j = b;
// do something here
free(data);
}
}
return 0;
}
我在data.i = a;
和data.j = b;
处出现错误:
error: request for member 'i' in something not a structure or union
error: request for member 'j' in something not a structure or union
如何修复这个错误?
另外,我应该在malloc(sizeof(struct Point))
之后使用free()
吗?
data
是一个指针。你必须说data->i
等等。
free()
。 data
是一个指向结构体的指针,而不是一个实际的结构体。您应该使用data->i
。
是的,如果你malloc()
一个结构体,那么你应该free()
当你完成它。
除了上面的答案,还有一点解释:
你有一个指向结构体的指针。首先,您应该使用星号操作符对它解引用,然后才能使用它。"->"操作符是"*v"的缩写形式,其中v是指向结构体的指针。这里是data->i
相当于*data.i
相关文章:
- 根据用户回答声明"Players"。用户选择玩家数量。播放器是结构体
- 结构体 S { int align; } 之间的区别;(struct 关键字后的名称)和 struct { int al
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 包含 std::list 的结构体的 C++ 初始化
- 结构体和类的不同大小(),彼此具有相同的字段类型
- 如何使用结构体的向量数组?
- 如何使用结构体在C++中更改这些代码?
- 无法在 Mosquitto MQTT Broker 插件上访问结构体 mosquitto 的元素
- 我应该如何在C++中使用结构体解决输入失败的问题?
- Qsort() 比较结构体整数的总和
- 如何使用迭代器指向结构体c++的向量
- 在C++中使用链表的堆栈实现中,访问结构体headNode成员count和top会导致运行时错误
- 如何获取结构体成员的地址
- 创建结构体向量,表达式:向量下标超出范围
- boost::任何带有结构体和无符号整数
- 如何在构造函数中初始化结构体的动态数组?
- 只写结构体的某些字段
- C++ push_back() 一个结构体到一个向量中
- c语言中具有指针数组的结构体
- 如何在c语言中使用结构体