Token pasting in c using a variable that increment

2019-09-15 19:41发布

I have a set of arrays :msg1[] msg2[] .... msgn[] . And I need to use the values in a while loop. as msgi[]. When I define it as #define MSG(a) msg##a and put it in a loop and increment i, it expands it to msgi?

5条回答
对你真心纯属浪费
2楼-- · 2019-09-15 20:11

It can't be done cause macros are replaced at compilation time not runtime, so it will be replaced once...

what you could do is use 2D array if there are in the same size or use array of arrays if there are in different sizes:

//once in your code you need to do this:
int array0[];
int array1[];
//...
int arrayX[]; //X should be replaced with a real number...
int **arrayOfArrays = new (int*)[X+1];
arrayOfArrays[0] = array0;
arrayOfArrays[1] = array1;
//...
arrayOfArrays[X] = arrayX;

//now you could use it like that anytime in your code:
int i;
for(i = 0; i < X; ++i)
{
    //Do whatever you want to do, like:
    arrayOfArrays[i][0] = 1234;
}
查看更多
Melony?
3楼-- · 2019-09-15 20:11

No, unfortunately it won't. C does not support runtime name lookups. Instead, you should use a two dimensional array of the form:

void** msg;

This will allow the arrays to be of different sizes and types, although you will have to cast to whatever type the array is.

查看更多
趁早两清
4楼-- · 2019-09-15 20:16

You can't do it that way. Instead you could create a new array, that contains pointers to the actual arrays:

int array1[...];
int array2[...];

int *all_arrays[] = { array1, array2 };
查看更多
乱世女痞
5楼-- · 2019-09-15 20:26

build your c code with gcc -E myfile.c and you will see the reason

this called preprocessor code. the prprocessor code is the code generated by your compilator before the compilation. in this code the compilator replace the macros in your origin code with the content of the macro.

your origin code:

for (i=0; i<10; i++) {
    for (j=0; j<10; j++)
        MSG(i)[j] = 3;
}

preprocessr code generated from the origin code (could be seen with gcc -E):

for (i=0; i<10; i++) {
    for (j=0; j<10; j++)
        msgi[j] = 3;
}

You can use 2D array instead

int msg[5][5];
查看更多
兄弟一词,经得起流年.
6楼-- · 2019-09-15 20:26

When I define it as #define MSG(a) msg##a and put it in a loop and increment i, it expands it to msgi?

No, it will not work that way, because the macro gets expanded before compilation, not after. You'll need a different approach, such as the 2D array suggested by @zakinster.

查看更多
登录 后发表回答