[英]Two Dimensional Array of Structs in C - how to declare and use
我一直试图获得一个非常简单的想法来在C语言中工作,但我什至无法降低语法。
该程序将从命令行接收一些输入,并使用它们来决定制作二维结构数组的大小。
然后,在for循环类型的情况下,我希望能够根据用户输入更改特定的未签名char。 因此,我首先构建一个二维结构数组,每个结构都包含一个无符号字符数组以及一个名称,然后我就可以对它们进行写入。
命令行参数是三个字符串。 First one is number of rows, second one is number of columns, third one is size of unsigned char array within each struct.
#include<stdio.h>
#include<stdbool.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
typedef struct {
unsigned char* Data;
char* name;
} myStruct;
myStruct* myArr[][];
int main(int argc, char *argv[])
{
int y = atoi(argv[0]);
int x = atoi(argv[1]);
int z = atoi(argv[2]);
myStruct* myArr[x][y];
for (int i = 0; i < x; i++)
{
for(int j = 0; j < y; j++)
{
myArr[i][j]=(myStruct*) malloc(sizeof(myStruct));
myArr[i][j].Data=(unsigned char*) malloc(sizeof(unsigned char)*z);
myArr[i][j].name = (char*) malloc(sizeof(char)*64);
}
}
//part II - change some entry of myArr based on input from user
//assume input has been taken in correctly
int h = 5;//5th row in myArr
int k = 7; // 7th column in myArr
int p = 9; //9th unsigned char in myArr[h][k].Data
unsigned char u = 241;//value to be written
char* newName = "bob";
myArr[h][k].Data[p]=u;
myArr[h][k].name=newName;
return 0;
}
此代码不起作用。 实际上,它不会编译。 有人可以帮我吗? 我只是试图将指针理解为从Java到C过渡的一种方式。这是我可以非常轻松地在Java中完成的事情,我也希望能够在C中实现。 我听说必须在main外部声明2 D数组,因此它在作用域内是全局的,因为堆栈的大小受到限制,而结构的2D数组可能会填充它。 有人也可以解释吗? 以及如何声明一个2D数组,其大小在运行时确定?
我打算为此使用C并且仅使用C。 因此,请不要向我提供C ++语法提示。 谢谢。
myArr[h][k].Data[p]=u;
myArr[h][k].name=newName;
应该
myArr[h][k]->Data[p]=u;
myArr[h][k]->name=newName;
因为它们是指针。 在您的循环中发生相同的错误。
myStruct* myArr[][];
该行无效且无意义,因为您在main()中重新定义了它。
如果要分配动态数组,可以使用:
myStruct **myArr = malloc(x * y * sizeof(**myArr));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.