[英]Read integers from text file into matrix in c - Access violation
嘗試從包含 10 行、每行 10 個數字的文本文件中讀取,並用空格分隔。 我想直接將每個數字保存到矩陣 numList 中的一個空間中。 真的不確定我的代碼有什么問題,我認為這可能是因為我沒有正確初始化矩陣或其他原因。 任何幫助表示贊賞
#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;
}
strcpy(numList[i][j],p) function 上出現問題,但我不知道為什么。
Output:在 asd.exe 中的 0x7C15EE87 (ucrtbased.dll) 處引發異常:0xC0000005:訪問沖突寫入位置 0xCCCCCCCC。
沒有為numList[i][j]
分配 memory 可以使用strdup
代替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++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.