This error never appeared before, I don't understand why it is happening. I am creating a C program to create an array and then realloc it to add more elements. Im applying many unecessary concepts in the same program to condense some knowledge.
#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;
}
error:
realloc(): invalid pointer
CodePudding user response:
It seems the problem is this call of scanf
for an object of the type _Bool
_Bool decision;
//...
scanf("%d", &decision);
Unfortunately there is no conversion specifier for objects of the type _Bool
that can be safely used in a call of scanf
.
Instead you could use an object of the type int
.
Another problem is using an incorrect conversion specifier in this call
scanf("%d", &newelements);
It seems you mean
scanf("%hu", &newelements);