strcpy从字符串数组到另一个字符串数组

时间:2014-04-04 00:41:21

标签: c c-strings

所以我创建了一个名为

的const字符串数组
  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]; 
strcpy(waiting[0], players[2]);

但是因为在这种情况下我不能使用strcpy(我相信),所以我对如何做到这一点感到有点失落?

1 个答案:

答案 0 :(得分:0)

以下内容应该有效。但是,您应该熟悉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;
}

输出:

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