debugging 在初始函数之外使用指针或Malloc时出现问题

zpjtge22  于 7个月前  发布在  其他
关注(0)|答案(1)|浏览(76)

我正在做一个项目,它要求调用输入并在一个单独的显示函数中输出它们。对于我的生活,我无法理解是什么导致了这个代码段的问题。我目前的目标是能够在这个Input函数之外打印 *(Names+j)。

/*additional info: The way i scanned in the strings and score values are meant to simulate how this would be tested, here is a sample of what the test vector will look like:

John Smith

85, 89, 79, 82

Latasha Green

79, 82, 73, 75

David Williams

62, 64, 71, 70

Albert James

55, 60, 54, 62

Nicole Johnson

95, 92, 88, 91

*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void GetInput(char **Names, int *PointerScore);
int main() {
char *Names[5];
int TestScoreArray[5][4];
int *PointerScore = &TestScoreArray[0][0];
GetInput(Names, PointerScore);
int j;
for (j = 0; j < 5; j++) {
printf("%s", *(Names+j));
}

//some loop to free malloc pointers
return 0;
}
void GetInput(char **Names, int *PointerScore) {
int i;
for (i = 0; i < 5; ++i) {
char temp1[256] = {'\0'};
char temp2[256] = {'\0'};
printf("Student %d's Name:\n", (i + 1));
scanf("%s%s", temp1, temp2);
strcat(temp1, " ");
strcat(temp1, temp2);
*(Names+i) = malloc(strlen(temp1));
strcpy(*(Names+i), temp1);
printf("Student %d's Scores:\n", (i+1));
scanf("%d, %d, %d, %d", (PointerScore+(i*5)), (PointerScore+(i*5)+1), (PointerScore+(i*5)+2), (PointerScore+(i*5))+3);
}
}

字符串
我已经将问题隔离到一个部分。我想知道这是否是第二次扫描和指针的一些超级利基问题。学生姓名抓取部分独立不会导致任何问题。它是当组合,使用相同的for循环并抓取值,这变得很奇怪。我不太熟悉malloc(),但它也可能是导致问题的原因。任何指针(没有双关语)都会有很大的帮助。

2o7dmzc5

2o7dmzc51#

1.没有为名称分配足够的内存;您忘记了终止空字符。更改

*(Names+i) = malloc(strlen(temp1));

字符串

Names[i] = malloc(strlen(temp1)+1);


(also使用更简单的索引表示法)。
1.在繁琐的指标计算中

scanf("%d, %d, %d, %d", (PointerScore+(i*5)), (PointerScore+(i*5)+1), (PointerScore+(i*5)+2), (PointerScore+(i*5))+3);


使用了错误的数字5,而不是4。请更改该数字,或者最好使用索引表示法:

void GetInput(char *Names[5], int Score[5][4])
…
    scanf("%d, %d, %d, %d", Score[i], Score[i]+1, Score[i]+2, Score[i]+3);


调用

GetInput(Names, TestScoreArray);


main为单位。

相关问题