所以,我有一个带有3个不同指针变量的结构。我需要做的是启动一个动态分配的矩阵,其中每个元素都是该结构的类型。我认为我已经正确地为矩阵和结构的成员分配了内存,但现在我不知道如何读取该矩阵的每个元素。我是初学者,请原谅我的编码风格或任何其他错误。我的问题是如何读取动态分配矩阵的元素,其中每个元素都是一个结构?
(我知道在结构中我可以写“char * x,* y,* z;”但我可以用这种方式看得更好)
typedef struct{char *type_present;
char *destination;
char *direction;
int no_available_presents;
}MAP;
int main(){
int max_line,max_col,i,j;
MAP **map;
//Allocating memory for the matrix
map=malloc(max_line * sizeof(MAP) );
for(i = 0; i < max_line; i++){
map[i]=calloc(col,sizeof(MAP));
}
//Allocating memory for the members of the structure
(*map)->destination=(char)malloc(1 * sizeof(char));
(*map)->direction=(char)malloc(1 * sizeof(char));
(*map)->type_present=(char)malloc(1 * sizeof(char));
/*Here is my problem, I don`t know if this is good, the warning is that
the format '%s' expects 'char' and the argument is '**char'.I know
that, I don`t know how to fix it but I think the real problem is that
my code here is simply incorrect.*/
for(i = 0; i < max_line; i++){
for(j = 0; j < max_col; j++){
scanf("%s\n", &(*map)->destination);
scanf("%s\n", &(*map)->direction);
scanf("%s\n", &(*map)->type_present);
scanf("%d\n", &(*map)->no_available_presents);
}
}
答案 0 :(得分:1)
第一个问题是这一行:
map=malloc(max_line * sizeof(MAP) );
在这里你需要一个指针数组,因此该行应为:
map=malloc(max_line * sizeof(MAP*) );
^
notice
下一个问题是这部分
//Allocating memory for the members of the structure
(*map)->destination=(char)malloc(1 * sizeof(char));
(*map)->direction=(char)malloc(1 * sizeof(char));
(*map)->type_present=(char)malloc(1 * sizeof(char));
出于几个原因这是错误的。首先,您只需初始化单个MAP而不是为所有MAP执行此操作。此外,当您想要存储字符串时,分配单个字符是没有意义的。
所以初始化应该是:
//Allocating memory for the members of the structure
for(i = 0; i < max_line; i++){
{
for(j = 0; j < max_col; j++){
{
map[i][j].destination = malloc(MAX_STRING_LENGTH * sizeof(char));
map[i][j].direction = malloc(MAX_STRING_LENGTH * sizeof(char));
map[i][j].type_present = malloc(MAX_STRING_LENGTH * sizeof(char));
}
}
如上所示,您只需map[i][j]
即可访问各个结构,因此您的scanf可以
scanf("%s\n", map[i][j].destination);
BTW:scanf("%s....
很糟糕,因为用户可能会溢出缓冲区。考虑使用fgets
或至少执行scanf("%42s...
,其中42是缓冲区长度(减1)。