所以我認爲問題在於獲取ref數組中的參考數字作爲字符串並將其轉換爲整數以轉換爲整數數組結果,並將其複製到頁面數組。由於我得到了分段錯誤11,我正在經歷一個數組的界限。不知道如何解決這個問題。C程序給我分段錯誤11
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
char ref[30];// array that holds reference string
int frame_size;// maximum number of frames is 8
// a frame holds a number thats in the reference stream.
int optimal_fault =0;
int lru_fault =0;// least recently used faults
int mfu_fault =0;// most frequently used faults
int lfu_fault =0;// least frequently used faults
int pages = 0;//counts how many times you've looped
//int page=0;//this will be the pages array
printf(" Please enter reference string: ");
fgets(ref, 30, stdin);
int num;
//printf("reference: %c", &ref);
printf(" Please enter the number of frames(no more than 8 allowed)\n");
scanf("%d",&frame_size);
int len = strlen(ref);
int results[len];
int page[len];
int k=0;
printf("len: %d:",len);
for(int i=0; ref[i]!= '\0'; i++)
{
if(isdigit(ref[i]))
{
num = sscanf(&ref[i], "%d", &results[i]);
printf("results: %d\n", results[i]);
page[k] = results[i];
printf("page: %d\n", page[k]);
k++;
i++;
}
}
return 0;
}
你正在循環體內再次增加'i ++'*兩次*,一次在'for'語句中。如果字符串長度是奇數,那麼你會錯過控制循環的''\ 0''終止符。 –
沒有這不是問題的第二個i ++是那裏的參考字符串格式。因爲它可以是1 2 3 23,如果我把i ++取出來,它不會看到23它會看到1 2 3 2 3 @WeatherVane –
如果你遇到了分段錯誤,用Valgrind或Dr. Memory運行它。這兩個程序都會告訴你哪行代碼非法訪問內存。 –