在 C 中将 strcpy 与字符串数组一起使用

发布于 2024-12-02 05:28:33 字数 206 浏览 1 评论 0原文

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

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

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

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

洛阳烟雨空心柳 2024-12-09 05:28:33

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

char c[20];

然后您可以使用 strcpy:

strcpy(c, "undefined");

如果您确实想要一个字符数组数组,则必须执行您所说的尝试:

// 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");

问题可能有您错过了结束 ",但我不知道这是否是粘贴错误。或者,问题可能是您使用 k 而没有 没有看到您收到的错误消息,我们就无法知道。

定义它,如果 你想将它们全部设置为该字符串,然后循环它们:

char c[20][70];

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

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(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 k without defining it, we can't know without seeing the error message you get.

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");
伴我老 2024-12-09 05:28:33

如果您想要的是 20 个字符串,每个字符串包含 70 个字符,那么您的第二个选项应该有效:

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

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]);

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

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];
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]);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文