1 year ago

#76774

test-img

xantico

How to access pseudo-random index via pointer?

*tabP[] contains addresses of p1[], p2[] and p3[]. Their indexes are declared as ranq which is random value between 0-3, but despite that, compiler output is always p1[0], never p1[1] or p1[2].

#include<stdio.h>
#include<time.h>
#include<stdlib.h>

int ranq;

int random()// Randomizer
{
    srand(time(0));
    ranq = rand() % 2;
}
int main()
{
    int i = 0;
    const char* p1[3] = { "aaa", "bbb", "ccc" };
    const char* p2[3] = { "ddd", "eee", "fff" };
    const char* p3[3] = { "ggg", "hhh", "iii" };
    const char** tabP[3] = { &p1[ranq], &p2[ranq], &p3[ranq] };
    do
    {
        random();
        printf(*tabP[i]);
        ++i;
    } while (i != 4);
    return 0;
}

Output: ( Every time I run the program)

aaa
ddd
ggg

Desired output should contain random contents of arrays. How to fix that?

arrays

c

pointers

srand

0 Answers

Your Answer

Accepted video resources