C语言 将 strcpy 与 C 中的字符串数组一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7251307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:32:15  来源:igfitidea点击:

Using strcpy with a string array in C

carrayscharstrcpy

提问by Adam

I have a character array defined as follows: char *c[20];
I'm trying to do: strcpy(c[k], "undefined);but it's not working

我有一个定义如下的字符数组:char *c[20];
我正在尝试:strcpy(c[k], "undefined);但它不起作用

I've also tried defining it as char c[20][70]with no luck.

我也尝试将其定义为char c[20][70]没有运气。

Edit: I actually know it's an array of character arrays, I need it like that.

编辑:我实际上知道它是一个字符数组数组,我需要它。

回答by Seth Carnegie

That's not a character array; that's an array of character pointers. Remove the *to make it a character array:

那不是字符数组;这是一个字符指针数组。删除*以使其成为字符数组:

char c[20];

Then you can use strcpy:

然后你可以使用strcpy:

strcpy(c, "undefined");

If you really did want an array of character arrays, you'll have to do what you said you tried:

如果您确实想要一个字符数组数组,则必须按照您所说的进行操作:

// array that holds 20 arrays that can hold up to 70 chars each
char c[20][70];

// copy "undefined" into the third element
strcpy(c[2], "undefined");

The problem could have been you're missing the closing ", I don't know if that was a paste error though. Or, the problem could have been that you're using kwithout defining it, we can't know without seeing the error message you get.

问题可能是您错过了结束语",但我不知道这是否是粘贴错误。或者,问题可能是您在使用时k没有定义它,我们无法在没有看到您收到的错误消息的情况下知道。

If you want to set them all to that string, then just loop over them:

如果要将它们全部设置为该字符串,则只需循环它们:

char c[20][70];

int i;
for (i = 0; i < 20; ++i)
    strcpy(c[i], "undefined");

回答by Miguel

If what you want is to have 20 strings of 70 chars each then your second option should work:

如果您想要的是每个 70 个字符的 20 个字符串,那么您的第二个选项应该可以工作:

char c[20][70];
for (int k = 0; k < 20; k++)
    strcpy(c[k], "undefined");

The char *c[20]definition is incorrect because you are just defining an array of 20 pointers, and the pointers are not initialized. You could make it work in this way:

char *c[20]定义不正确,因为你只是定义的20个指针数组,指针不会被初始化。你可以让它以这种方式工作:

char *c[20];
for (int k = 0; k < 20; k++) {
    c[k] = malloc(70);
    strcpy(c[k], "undefined");
}

// then when you are done with these strings
for (int k = 0; k < 20; k++)
    free(c[k]);