【发布时间】:2016-04-13 20:29:06
【问题描述】:
我正在尝试自学 C,所以我编写了一个程序来保存成绩簿的记录!在我努力学习指针的过程中,我试图将我开始的数组项目之一转换为指针。我想将我的二维数组转换为指针。下面是我使用 2d 数组的原始程序,下面是我尝试将其转换为 2d 指针数组。
原始程序
int numberPeople, choice, i, j;
char people[15][3][100];
printf("Please indicate number of records you want to enter (min %d, max %d): ", 5, 15);
scanf("%d", &numberPeople);
while ((numberPeople < 5) || (numberPeople > 15)) {
printf("\nNumber not in specified range, try again.\n");
printf("Please indicate number of records you want to enter (min %d, max %d): ", 5, 15);
scanf("%d", &numberPeople);
}
printf("\n");
while ((getchar()) != '\n'); // flush the return (and anything else) after the number input above
printf("Enter the first name, last name, and grade (put a space in between each): \n");
for (i = 0; i < numberPeople; i++) {
char tempArr[MAXIMUM_LINE_LENGTH];
fgets(tempArr, MAXIMUM_LINE_LENGTH, stdin);
char *token = strtok(tempArr, " ");
for (j = 0; j < DATA_FIELDS && token != NULL; j++) {
strncpy(people[i][j], token, MAXIMUM_DATA_LENGTH);
token = strtok(NULL, " \r\n");
}
}
尝试二维数组 -> 指针
int numberPeople, choice, i, j;
char* people;
printf("Please indicate number of records you want to enter (min %d, max %d): ", 5, 15);
scanf("%d", &numberPeople);
people = (char*)(malloc(numberPeople*DATA_FIELDS*sizeof(char)));
while ((numberPeople < 5) || (numberPeople > 15)) {
printf("\nNumber not in specified range, try again.\n");
printf("Please indicate number of records you want to enter (min %d, max %d): ", 5, 15);
scanf("%d", &numberPeople);
}
printf("\n");
while ((getchar()) != '\n'); // flush the return (and anything else) after the number input above
printf("Enter the first name, last name, and grade (put a space in between each): \n");
for (i = 0; i < numberPeople; i++) {
char* tempArr;
fgets(tempArr, 100, stdin); // Thread 1: EXC_BAD_ACCESS code=1 address=0x0
char *token = strtok(tempArr, " ");
for (j = 0; j < 3 && token != NULL; j++) {
strncpy(people, token, 50);
token = strtok(NULL, " \r\n");
}
}
在人员输入步骤期间,它会中断。它适用于第一个条目,但随后遇到断点(我正在使用 Xcode),它显示“EXC_BAD_ACCESS”,我不太确定这是什么意思,任何提示都会有所帮助,谢谢!
【问题讨论】:
-
第一件事:
numberPeople未初始化或为零,但用于malloc -
第二件事:你的第一个例子是一个数组数组。在将其移动到动态存储时,指向最主要维度的基础元素类型的指针应该是您的目标:即
char (*people)[3][100];,假设它是您作为可变参数定位的15。 -
哇哦,菜鸟的错误。我刚刚编辑并将 numberPeople 进一步向下移动,以便现在它具有价值,谢谢! @EugeneSh。
-
我会注意的。谢谢! @WhozCraig 是否可以只用指针(没有任何数组)来制作这个程序?这就是我想要完成的。再次感谢!
-
老实说,我不会。如果您可以使用指向动态数组数组的单个指针来管理它,我会认真考虑为什么要以其他方式进行操作。大多数时候,软件工程就是做你应该的事情;不是你可以。指向动态数组的指针的动态数组的指针的动态数组在很大程度上倾向于后者,而不是前者。也就是说,你可以做到,当然,但你最好更加适应这似乎表明的动态管理。