Posts

Showing posts with the label macros

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? 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 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(si...

C macros using enum

C macros using enum I am trying to use #if macros by defining the type of operation to invoke the right code, So i made a very simple example similar to what I am trying to do: #include <stdio.h> enum{ADD,SUB,MUL}; #define operation ADD int main() { int a = 4; int b = 2; int c; #if (operation == ADD) c = a+b; #endif #if (operation == SUB) c = a-b; #endif #if (operation == MUL) c = a*b; #endif printf("result = %i",c); return 0; } But unfortunately that does not work I get the following result = 8 ... if I replace The operation with numbers it works fine .... But i want it to work as it is described above. result = 8 Any help "unfortunately that does not work" is not a very good description. Do you get a compile error? a run-time crash? output different from what you expect? "Not working" covers a lot of cases without describing any. – abelenky ...