trying to read in from a text file with 10 lines of 10 numbers separated by spaces. I want to directly save each number into a space in the matrix numList. Really not sure what the problem is with my code, I think it might be because i'm not initializing the matrix correctly or something. Any help appreciated
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
FILE* fpointer = fopen("numbers.txt", "r");
if (fpointer == NULL) {
printf("No file found");
return 1;
}
// INITIALISE MATRIX
char* numList[10][10];
char buffer[300];
// COPY NUMBERS INTO MATRIX
int i = 0;
while (fgets(buffer, 300, fpointer)) {
int j = 0;
char* p = strtok(buffer, " ");
while ((p != NULL)&&(j<10)) {
printf(" %s ",p);
strcpy(numList[i][j],p);
p = strtok(NULL, " ");
j++;
}
printf("\n");
i++;
}
printf("\n\n");
//Print Final Matrix
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
printf("%s ", numList[i][j]);
}
printf("\n");
}
fclose(fpointer);
return 0;
}
Problem is occurring on the strcpy(numList[i][j],p) function but i'm not sure why.
Output: Exception thrown at 0x7C15EE87 (ucrtbased.dll) in asd.exe: 0xC0000005: Access violation writing location 0xCCCCCCCC.
No memory is allocated for numList[i][j]
You can use strdup
instead of strcpy
while (fgets(buffer, 300, fpointer)) {
int j = 0;
char* p = strtok(buffer, " ");
while ((p != NULL)&&(j<10)) {
printf(" %s ",p);
numList[i][j] = strdup(p);
p = strtok(NULL, " ");
j++;
}
printf("\n");
i++;
}
User contributions licensed under CC BY-SA 3.0