dynamic define and allocate pointers
dynamic define and allocate pointers
I want to dynamically define and allocate pointers:
#include<stdio.h>
#define def_var(type,name,i) type name##i
#define var(name,i) name##i
void main(){
int i;
for (i=0;i<10;i++){
def_var(float,*ww,i)=NULL;
}
for (i=0;i<10;i++){
var(ww,i)=(float *)malloc(100);
}
}
But when I compile it, lots of error come up. Can anybody help fix it?
for
Also you're using
malloc
incorrectly. You need to specify the size in bytes of what you want to allocate, so to allocate 100 float you want malloc(sizeof(float)*100)
– Chris Turner
Jun 29 at 15:53
malloc
malloc(sizeof(float)*100)
@Acorn no - it's 10
float *
, but OP has put the * in the wrong place.– Chris Turner
Jun 29 at 15:55
float *
It's pointless to use macros for making your code less readable. Is this an XY Problem? What are you actually trying to achieve?
– Jabberwocky
Jun 29 at 15:56
Why are you using a macro to create numbered variables instead of just using an array?
– Barmar
Jun 29 at 15:59
2 Answers
2
You can't do what you're trying to do. Preprocessor macros are expanded at compile time, they can't depend on run-time variable values. So
def_var(float,*ww,i)=NULL;
is expanded into
float *wwi = NULL;
It doesn't, and can't, replace i
with the value of the variable, it just performs text substitution.
i
Also, variable declarations have block scope, so any variables declared inside the for
loop go away when the loop finishes.
for
Just declare an array of pointers.
float *ww[10];
for (int i = 0; i < 10; i++) {
ww[i] = malloc(100 * sizeof(float *));
}
If ww
is supposed to represent 10 arrays of 100 floats each (known numbers at compile time), then just use a multi-dimensional array:
ww
float ww[10][100];
and index accordingly when used (eg: ww[7][93] = 6;
).
ww[7][93] = 6;
If 'ww' must contain dynamically allocated pointers as you say, then use (where each element is a pointer to an array of 100 floats)
float (*ww[10]) [100];
for (i=0;i<10;i++){
ww[i]=malloc(sizeof(float)*100);
}
and index accordingly when used (eg: (*(ww[7]))[93] = 6;
or ww[7]->[93] = 6;
).
(*(ww[7]))[93] = 6;
ww[7]->[93] = 6;
Remember to free each when done.
for (i=0;i<10;i++){
free(ww[i]);
}
Caution: Remember malloc
will not intialize the newly allocated memory - that is up to you! Strongly recommended to use calloc
instead to zero-out the memory instead, so it is in a known state.
malloc
calloc
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
There is no point telling us there are errors if you don't include them in your question! But it's obvious the problem is that you're declaring variables in your first
for
loop and trying to use them in the second one.– Chris Turner
Jun 29 at 15:50