這個錯誤以前從未出現過,我不明白為什么會這樣。我正在創建一個 C 程式來創建一個陣列,然后重新分配它以添加更多元素。我在同一個程式中應用了許多不必要的概念來濃縮一些知識。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// ALWAYS when doing a definition of new elements in a arrays, NEVER use size as a parameter
// because if you assign one element as one, it will reset the value of size then reseting
// size < sizenew.
// Ex: Do not do:
//
// for (size; size < newsize; size ) scanf ("%hu", &size)
//
// the number you choose for scanf will affect the number of times the loop will do, because size
// is a parameter of while
int main()
{
_Bool decision;
int* array;
unsigned short size, newelements, oldsize, add, minus_oldsize, newsize, i, j;
printf("Hello! put the size of the initial int array!\n");
scanf("%hu", &size);
array = malloc(size * 4);
printf("Put the array elements one by one\n");
for (i = 0; i < size; i ) scanf("%d", array i);
printf("This is your array:\n");
for (j = 0; j < size; j ) printf("%d\n", *(array j));
printf("Do you want to add more elements? no(0) yes(1)\n");
scanf("%d", &decision);
if (decision != 1) return -1;
printf("How many elements you want to add?\n");
scanf("%d", &newelements);
newsize = size newelements;
array = realloc(array, newsize * 4);
free(array);
return 0;
}
錯誤:
realloc(): invalid pointer
uj5u.com熱心網友回復:
似乎問題在于scanf對型別物件的呼叫_Bool
_Bool decision;
//...
scanf("%d", &decision);
不幸的是,沒有_Bool可以在呼叫scanf.
相反,您可以使用型別的物件int。
另一個問題是在此呼叫中使用了不正確的轉換說明符
scanf("%d", &newelements);
看來你的意思
scanf("%hu", &newelements);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/431084.html
