-1
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

int main()
{
    const char mot1[] = "POMME", mot2[] = "POIRE", mot4[] = "PASTEQUE", mot5[] = "MELON", mot6[] = "ORANGE", mot7[] = "FRAISE", mot8[] = "FRAMBOISE", mot9[] = "CITRON", mot10[] = "MANGUE";

    srand(time(NULL));

    int index = rand() % 10 + 1;

    char secret[100] = "";

    strcpy(motindex, secret);

    printf("Secret is now %s\n", secret);

    return 0;
}

Here's the code I made to generate a random secret word from a range of const char.

I want to substitute index in strcpy(motindex, secret);. How can I do that ?

Amin NAIRI
  • 2,292
  • 21
  • 20

2 Answers2

5

You can't; strings are not identifiers and identifiers are not strings.
(Variable names don't even exist in the program - they only exist in the source code.)

Use an array and use the index as "name".

I also suspect that you want to copy the secret the other way around, so secret holds the name of a fruit.

int main()
{
    const char* mot[]= {"POMME", "POIRE", "PASTEQUE", "MELON", "ORANGE", "FRAISE", "FRAMBOISE", "CITRON", "MANGUE"};

    srand(time(NULL));
    int index = rand() % 9; /* You only have nine strings... */

    char secret[100] = "";

    strcpy(secret, mot[index]);

    printf("Secret is now %s\n", secret);

    return 0;
}
molbdnilo
  • 64,751
  • 3
  • 43
  • 82
  • Okay, that's why, I inverted things in the `strcpy` function. Thanks for pointing that out. The result gave me the good answer. Only one question remaining : why using bidimensionnal array ? And why 128 ? – Amin NAIRI Apr 13 '16 at 09:49
  • 2
    @Gradiuss I've edited the code to match what I believe you're after. (The two dimensions were necessary if you wanted to modify the strings, and 128 was a completely arbitrary "power of 2 that has plenty of room".) – molbdnilo Apr 13 '16 at 09:54
2

I think two-dim array can solve your problem the codes list below

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

#define SC_NUM  10
int main(){
    const char motSecret[SC_NUM][100] = {
        "POMME",
        "POIRE",
        "PASTEQUE",
        "MELON",
       //some more const secret
    };

    int index = ((rand() % SC_NUM) + SC_NUM) % SC_NUM;
    char secret[100];
    strcpy(secret, motSecret[index]);
    printf("Secret is now %s\n", secret);
   return 0;
}
Chunlei Ma
  • 66
  • 2