我正在處理的這個來自hackerRank的挑戰通過測驗運行成功編譯,并通過各種輸入給出正確答案。但是當我提交并且代碼像這樣以大量數字運行時,我遇到了分段錯誤。
我最好的猜測是我在為動態二維陣列分配記憶體時犯了某種錯誤。
由于我所有的測驗運行都成功編譯并給出了正確的結果,我不知道為什么它不起作用。
#include <stdio.h>
#include <stdlib.h>
/*
* This stores the total number of books in each shelf.
*/
int* total_number_of_books;
/*
* This stores the total number of pages in each book of each shelf.
* The rows represent the shelves and the columns represent the books.
*/
int** total_number_of_pages;
int main()
{
int total_number_of_shelves;
scanf("%d", &total_number_of_shelves);
int total_number_of_queries;
scanf("%d", &total_number_of_queries);
//_______________________________________________________________________//
// All malloc() declarations writen by me are here : //
// My guess is, one of this statement is causing the bug. //
//_______________________________________________________________________//
total_number_of_books=(int *)malloc(sizeof(int)*(total_number_of_shelves*1100));
total_number_of_pages=(int **)malloc(sizeof(int*)*total_number_of_shelves);
for (int tnos=0; tnos<total_number_of_shelves; tnos )
{
total_number_of_pages[tnos]=(int *)malloc(sizeof(int)*1100);
}
while (total_number_of_queries--) {
int type_of_query;
scanf("%d", &type_of_query);
if (type_of_query == 1) {
//___My code starts here.___//
int x, y, index;
scanf("%d %d", &x, &y);
index=0;
while( total_number_of_pages[x][index]!=0 )
{
index ;
}
total_number_of_pages[x][index] = y;
total_number_of_books[x] ;
//_______________________________________________________________//
//All code below is a template which was provided by the website.//
} else if (type_of_query == 2) {
int x, y;
scanf("%d %d", &x, &y);
printf("%d\n", *(*(total_number_of_pages x) y));
} else {
int x;
scanf("%d", &x);
printf("%d\n", *(total_number_of_books x));
}
}
if (total_number_of_books) {
free(total_number_of_books);
}
for (int i = 0; i < total_number_of_shelves; i ) {
if (*(total_number_of_pages i)) {
free(*(total_number_of_pages i));
}
}
if (total_number_of_pages) {
free(total_number_of_pages);
}
return 0;
}
uj5u.com熱心網友回復:
realloc()當您需要在其中放置新元素時,您應該使用來增長動態陣列。在您的代碼中,您一開始只進行一次分配。
例如,在開始時寫這個(在你scanf()得到total_number_of_shelves和之后total_number_of_queries):
total_number_of_books = malloc(total_number_of_shelves * sizeof(int));
total_number_of_pages = malloc(total_number_of_shelves * sizeof(int*));
// TODO: you should initialize every element of the first array to `0`,
// and every element of the second array to `NULL`
當你需要在里面放入一個新元素時,你可以使用realloc():
total_number_of_books[x] = 1;
total_number_of_pages[x] = realloc(total_number_of_pages[x], total_number_of_books[x] * sizeof(int));
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/322009.html
