开发者

C - How to iterate in a for loop the same istruction every time on a different variable

I have a list of variables called num1, num2, num3, etc..

Now I want to assign a 开发者_如何学Pythonrandom value (between 1 and 20) to each of these variables in a for loop. The problem is that i can't imagine an effective way to repeat the 1 + rand() % 20; instruction on the next variable at each for iteration.

The only way I found is to repeat the istruction manually for every variable which obviously is not an elegant solution:

num1  = 1 + rand() % 20;
num2  = 1 + rand() % 20;
num3  = 1 + rand() % 20;
...

How to achieve this?


Use an array.

int num[j];
for (i=0; i<j; i++)
{
  num[i] = 1 + rand() % 20;
}


Make an array of pointers to your variables and loop over that.


This is the only solution (which does not involve messing with the stack and assuming a certain layout of the variables in-memory) if you have separate variables.

The proper solution would be using an array so you can use a loop to assign something to each array element.


If you don't have those numbers as an Array, use an Array of Pointers pointing to those numbers:

int num1,num2,num3;
int * p[3] = { &num1, &num2, &num3 };

for (int i = 0 ; i < 3 ; i++)
*(p[i]) = 1 + rand() % 20;


Just for fun. DO NOT TRY THIS AT HOME! THIS IS EXTREMELY EXTREMELY BAD!

#include <stdio.h>
int main (int argc, char const* argv[])
{
    int num1, num2, num3;
    int i, *num = &num1;
    for(i = 0; i < 3; i++, num--){
        *num = 1 + rand() % 20;
    }
    return 0;
}


Other people have mentioned setting up an array pointer to hold pointers to the variables.

Another approach would be to create a variable argument function (like printf) and pass the pointers as arguments and passing a count to indicate the number of items in the list or NULL to indicate the end of the list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜