'array type 'int [0]' is not assignable
C++ has templates, allowing you to make a function that receives different types of variables. But in C I can't use templates. The only way I know is to use macros. I tried it to make a function to resize an array, but unlike a function, a macro takes the array without converting it to a pointer. So I can't use realloc() with it.
When I try this array type int [0] is not assignable error appears. What I can do? (I am making this just for testing the macros and understand it. I don't actually need to make a function for arrays, so please don't tell me about any standard function that can do that.)
Here is my code :
#include <stdio.h>
#include <stdlib.h>
#define size(__list__) ({unsigned int size = sizeof(__list__)/sizeof(__list__[0]); size;})
// Size function works without any error.
#define resize(__list__,__new_size__) ({__list__ = realloc(__list__,__new_size__);})
//But resize doesnt work.
int main() {
int arr[0];
resize(arr,10); // -- Doesnt work
printf("%d",size(arr));
return 0;
}
Eidt : i know thats i can't use realloc on a array. But can i convert it to pointer or takes it size and create a new array?
like :
#define resize(__list__,__new_size__) ({'type_of_list' new_list[__new_size__];})
Solution 1:[1]
This is a bit of an interesting problem because in C you have to decide if you want an array to be resizable or if you want to be able to tell how long it is. If you put an array on the stack, the sizeof operator is able to tell you how many bytes it takes up, but if you allocate an array in the heap, the sizeof operator can only tell you how many bytes the pointer that points to it takes up.
To solve your problem, you need to allocate an array in the heap, but manually keep track of the number of elements you resized it to last time.
This would be my solution (I tried to keep as much of your coding style as I could):
#include <stdio.h>
#include <stdlib.h>
struct resizable_list{
size_t num_elements; //Array length here
int *array; //Pointer to resizable array here
};
#define size(list) list.num_elements
#define resize(list,new_size) {list.array=realloc(list.array,new_size*sizeof(int));list.num_elements=new_size;}
int main(){
struct resizable_list arr = (struct resizable_list){.num_elements = 0,.array = NULL};
resize(arr,10); //Macro realloc()s the array and stores 10 in num_elements
printf("%zd\n",size(arr));
}
Which is probably a little more complex than you were hoping but it will work
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
