Question

So I created a const string array of names

  const char *players[10];
  players[0] = "Anselm";
  players[1] = "Otto";
  players[2] = "Fedor";
  players[3] = "Juergen";
  players[4] = "Ulrich";
  players[5] = "Eugen";
  players[6] = "Meinrad";
  players[7] = "Gotthard";
  players[8] = "Frank";
  players[9] = "Matthaeus";

I want to be able to copy any one of the players from this string array to another

this array:

char waiting[10][20]; 
strcpy(waiting[0], players[2]);

But since I can't use strcpy (I believe) in this case, I'm at a bit of a loss as to how I would do this?

Was it helpful?

Solution

The following should work. However, you should familiarise yourself with the use of malloc().

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

int main(int argc, const char * argv[])
{

    const char *players[10];
    players[0] = "Anselm";
    players[1] = "Otto";
    players[2] = "Fedor";
    players[3] = "Juergen";
    players[4] = "Ulrich";
    players[5] = "Eugen";
    players[6] = "Meinrad";
    players[7] = "Gotthard";
    players[8] = "Frank";
    players[9] = "Matthaeus";

    char waiting[10][20];
    for (int i = 0; i < 10; i++){
        strcpy(waiting[i], players[i]);
    }
    for (int i = 0; i < 10; i++){
        printf("waiting[%d]: %s\n", i, waiting[i]);
    }

    return 0;
}

Output:

waiting[0]: Anselm
waiting[1]: Otto
waiting[2]: Fedor
waiting[3]: Juergen
waiting[4]: Ulrich
waiting[5]: Eugen
waiting[6]: Meinrad
waiting[7]: Gotthard
waiting[8]: Frank
waiting[9]: Matthaeus
Program ended with exit code: 0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top