提问人:kovacskurt 提问时间:10/26/2023 更新时间:10/26/2023 访问量:18
在初始函数之外使用指针或 Malloc 时遇到问题
Trouble using Pointers or Malloc outside of initial function
问:
我正在处理这个项目,它要求调用输入并在单独的显示函数中输出它们。就我而言,我无法理解是什么导致了此代码段中的问题。我目前的目标是能够在此输入函数之外打印 *(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()不太熟悉,但也可能是导致问题的原因。任何指针(没有双关语)都将是一个巨大的帮助。
答:
0赞
Armali
10/26/2023
#1
未为名称分配足够的内存;您忘记了终止 null 字符。改变
*(Names+i) = malloc(strlen(temp1));
自
Names[i] = malloc(strlen(temp1)+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
评论