我正在使用动态2D数组编写剧院程序。要存储预订详情,我使用结构。 当我尝试初始化2D数组的每个索引中的一个变量时,我收到未处理的异常错误。
错误的功能:
void initializing_tickets(ticket **arrayPtr, int row, int col){
int i, j, counter;
for(i = 0; i < row; i++)
{
for(j = 0; j < col; j++)
{
(*(arrayPtr + i) + j) -> id = 0; // debugger explains that expression cannot be evaluated
printf("%d ", (*(arrayPtr + i) + j) -> id);
}
printf("\n");
}
} //end of initializing_tickets()
我的计划到目前为止:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
/* Structures */
typedef struct Theater
{
int id;
int status;
char name[20];
char phone[15];
} ticket;
/* Global variables */
ticket **array2D; // pointer to a 2D array
/* Constructors */
void create_Theater(int *row, int* col);
void test();
void loop_array(ticket **arrayPtr, int row, int col);
void initializing_tickets(ticket **arrayPtr, int row, int col);
int main(void)
{
int row = 0, col = 0;
create_Theater(&row,&col);
initializing_tickets(array2D, row, col);
//loop_array(array2D, row, col);
//test();
printf("\n\n");
system("pause");
return(0);
}
void create_Theater(int *row, int* col)
{
int r = 0, c = 0;
int i;
assert(row);
assert(col);
*row = r;
*col = c;
printf("Please enter the row dimensions of the Theater\n");
scanf("%d", row);
printf("Please enter the column dimensions of the Theater\n");
scanf("%d", col);
array2D = (ticket**)malloc(r*sizeof(ticket*));
for (i = 0;i<r;i++)
{
array2D[i] = (ticket*)malloc(c*sizeof(ticket));
}
} // end of create_Theater()
void initializing_tickets(ticket **arrayPtr, int row, int col){
int i, j, counter;
for(i = 0; i < row; i++)
{
for(j = 0; j < col; j++)
{
(*(arrayPtr + i) + j) -> id = 0; // debugger explains that expression cannot be evaluated
printf("%d ", (*(arrayPtr + i) + j) -> id);
}
printf("\n");
}
} //end of initializing_tickets()
void loop_array(ticket **arrayPtr, int row, int col)
{
int i, j;
for(i = 0; i < row; i++)
{
printf("Row is ok");
for(j = 0; j < col; j++)
{
printf("Col is ok");
}
}
}
我认为数组没有正确分配给内存,但我找不到错误。 谢谢你的关注!
答案 0 :(得分:2)
将您的功能更改为:
void create_Theater(int* row, int* col){
int i;
assert(row);
assert(col);
printf("Please enter the row dimensions of the Theater\n");
scanf("%d", row);
printf("Please enter the column dimensions of the Theater\n");
scanf("%d", col);
array2D = (ticket**)malloc((*row)*sizeof(ticket*));
for (i = 0;i<(*row);i++)
{
array2D[i] = (ticket*)malloc((*col)*sizeof(ticket));
}
} // end of create_Theater()
有效。