我正在制作一個程式,可以根據用戶輸入制作陣列并將其保存在 csv 檔案中。然后用戶可以使用存盤的陣列執行矩陣和向量運算。當我開始使用 csv 檔案(最初在 clion 上)時,我開始收到錯誤訊息:“行程已完成退出代碼 139(被信號 11 中斷:SIGSEGV)”除錯后我發現錯誤“EXC_BAD_ACCESS(代碼 = 2,地址 = 0x7ff7b202dff8 )”。然而,該程式在 relit 中運行時仍然有效。可悲的是,雖然在我寫了 60 -65 行以便在每次運行該函式時創建一個不同的 csv 檔案后,我開始收到錯誤:“信號:分段錯誤(核心轉儲)”在 relit 上。什么可能導致這些錯誤?這是我在 relit 上的代碼:
“https://replit.com/@iasonaszak/the-matrix#main.c”
預先感謝您的幫助!!
這是我的代碼:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "time.h"
#include <math.h>
#include <stdbool.h>
int a;
char c[20];
int num;
bool b = true;
int main() {
while (b ==true){
void create_array();
void delete_array();
int user_answer;
time_t t;
srand((unsigned) time(&t));
printf(
" 1.create an array\n 2.load an array\n 3.Show available arrays\n 4.Delete array\n 5.Vector operations \n 6.Matrix operations"
) ;
printf("Please choose one of the following options!\n");
scanf("%d" , &user_answer);
if (user_answer == 1){
create_array( );
}
else if (user_answer == 4){
delete_array();
}
return 0;
}
}
void create_array(){
int rows;
int cols;
int i;
int j;
int matrix[i][j];
printf("how many columns would you like your array to have");
scanf("%d" ,&cols );
printf("how many rows would you like your array to have");
scanf("%d" ,&rows );
char filename[80];
FILE *fout = fopen(filename, "wt");
FILE *last = fopen("lastnum.csv" , "w");
fgets(c , 20 , last);
num = atoi(c);
snprintf(filename, sizeof(filename), "prefix.%d.csv", num);
for (i = 0 ; i < rows; i ){
printf("\n");
fprintf(fout , "\n");
for (j = 0 ; j < cols; j ){
scanf("%d", &matrix[i][j]);
char str[(int)((ceil(log10(matrix[i][j])) 1)*sizeof(char))];
sprintf(str , "%d " , matrix[i][j]);
fprintf(fout ,"%s" , str);
}
}
printf("Your array was saved successfuly inside a csv file");
num ;
}
void delete_array(){
remove("prefix.0.csv");
remove("prefix.1.csv");
remove("prefix.2.csv");
remove("prefix.3.csv");
remove("prefix.4.csv");
remove("prefix.5.csv");
remove("prefix.6.csv");
remove("prefix.7.csv");
remove("prefix.8.csv");
remove("prefix.9.csv");
printf("all arrays were deleted");
}
void preview_arrays(){
FILE *F0 = fopen("prefix.0.csv" , "r");
}
uj5u.com熱心網友回復:
這三行會導致一個問題:
char str[(int)((ceil(log10(matrix[i][j])) 1)*sizeof(char))];
sprintf(str , "%d " , matrix[i][j]);
fprintf(fout ,"%s" , str);
表達(int)((ceil(log10(matrix[i][j])) 1將產生1從矩陣值1,但char str[1];為空終止字串將是不夠的。
當矩陣值為<= 0對數時,未定義。在我的測驗中,0它試圖定義char str[-2147483648];
您不str用于任何其他用途,因此我建議您洗掉這三行并使用這一簡單的行代替:
fprintf(fout,"%d ", matrix[i][j]);
更新
另一個故障是檔案打開:錯誤模式
FILE *last = fopen("lastnum.csv" , "w");
應該
FILE *last = fopen("lastnum.csv" , "r");
并始終檢查是否fopen()成功!
if(fout == NULL) {
/* handle error */
}
if(last == NULL) {
/* handle error */
}
并始終檢查是否fgets()成功。
if(fgets(c , sizeof c , last)) == NULL) { // changed the 'magic' 20
/* handle error */
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/397065.html
下一篇:CSV檔案資料替換
