I am working on this one project which asks to call inputs and output them in a separate display function. For the life of me I can not understand what is causing the issue in this code segment. My goal currently is to be able to print *(Names+j) outside of this Input function.
/*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);
}
}
I've isolated the issue to one part. I wonder if it is some super niche issue with the 2nd scanf and pointers. The student name grabbing segment independently does not cause any issues. It is when combined, using the same for loop and grabbing the values that it gets weird. I'm not as familiar with malloc() but it may also be that causing the issue. Any pointers (no pun intended) would be a huge help.
Not enough memory is allocated for a name; you forgot the terminating null character. Change
*(Names+i) = malloc(strlen(temp1));
to
Names[i] = malloc(strlen(temp1)+1);
(also use the simpler index notation).
In the cumbersome index calculations
scanf("%d, %d, %d, %d", (PointerScore+(i*5)), (PointerScore+(i*5)+1), (PointerScore+(i*5)+2), (PointerScore+(i*5))+3);
the wrong number 5
is used instead of 4
. Change that, or better use index notation:
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);
called by
GetInput(Names, TestScoreArray);
in main
.