Reputation:
Im running into an issue when Im trying to compile my program.
Errors:
main.c:26:42: error: invalid operands to binary * (have 'long unsigned int' and 'int *')
array = (int*) malloc(sizeof(int)* size);
^
main.c:30:50: error: invalid operands to binary * (have 'long unsigned int' and 'int *')
array = (int*) realloc(array, sizeof(int)* size) ;
Below is the relevant code:
int* arraySize(int* array, int* size)
{
size = 0;
while ((size > 20) || (size < 1))
{
printf("What is the size of your array? (1 - 20)\n");
scanf("%d", &size);
if ((size > 20) || (size < 1))
{
printf("Invalid selection.\n");
}
}
//checking if array has been allocated before
if(array = NULL)
{
array = (int*) malloc(sizeof(int)* size);
}
else
{
array = (int*) realloc(array, sizeof(int)* size) ;
}
printf("\nSize of array: array[%d]\nReturning...", size);
return array;
}
Can someone please explain to me what’s going on?
TIA
Upvotes: 0
Views: 7296
Reputation: 41
what is the point of making a dynamic array? can't you declare the array as bellow or something like this?
int array[size];
Upvotes: 0
Reputation: 715
Take a look in this line:
array = (int*) malloc(sizeof(int)* size);
and your method signature:
int* arraySize(int* array, int* size)
its clear that your size is a pointer, and you want to allocate some memory as per the size value; but what you have tried here addressing size address. So, it should be as following:
array = (int*) malloc(sizeof(int) * *size);
Always remember, for
int *size;
size means address of size and *size means values in that address.
Upvotes: 0
Reputation: 724
Another unrelated issue you have: your if
statement is assigning the value NULL
to array
. You should be using a double equals sign.
Upvotes: 0
Reputation: 2992
You've one * too much in argument size. This makes size a poitner to int. Which in turn needs to be dereferenced (*size rather than simply size) to use the value pointer points to. But i assume its a mistake and u didnt want to make size a pointer.
Change to:
int* arraySize(int* array, int size)
Upvotes: 2