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

问题描述 投票:0回答:1

我正在开发这个项目,该项目要求调用输入并在单独的显示函数中输出它们。对于我的一生,我无法理解是什么导致了这个代码段中的问题。我当前的目标是能够在此输入函数之外打印 *(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);
}
}

我已将问题隔离到一个部分。我想知道第二个 scanf 和指针是否存在一些超级小众问题。独立抓取学生姓名片段不会造成任何问题。当组合使用相同的 for 循环并获取值时,它会变得很奇怪。我对 malloc() 不太熟悉,但这也可能是导致问题的原因。任何指示(没有双关语)都会有很大的帮助。

pointers debugging malloc scanf
1个回答
0
投票
  1. 没有为名称分配足够的内存;您忘记了终止空字符。改变

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

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

    (也使用更简单的索引符号)。

  2. 在繁琐的指数计算中

    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

© www.soinside.com 2019 - 2024. All rights reserved.