将字符串分配给二维数组

发布于 2024-09-04 06:02:00 字数 168 浏览 1 评论 0原文

char in[100], *temp[10],var[10][10];
int i, n = 0,
double val[10];
var[0][]="ANS";

我想将一个字符串分配给 var[0][0,1,2] ,即“ANS”,但不起作用,我无法弄清楚我在哪里错了

char in[100], *temp[10],var[10][10];
int i, n = 0,
double val[10];
var[0][]="ANS";

I want to assign a string to var[0][0,1,2] which is 'ANS', but does not work and i cannot figure where i am wrong about this

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

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

发布评论

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

评论(3

心头的小情儿 2024-09-11 06:02:00

也许改为使用,

strncpy(var[0], "ANS", 3);

Perhaps instead using,

strncpy(var[0], "ANS", 3);
﹏雨一样淡蓝的深情 2024-09-11 06:02:00

你已经回答了你自己的问题。您想将 var[0][0,1,2,3] 分配给“ANS”,对吗?那么“ANS”是一个字符数组,ans[0,1,2,3](不要忘记空终止符)。所以你必须单独分配每一项。在 C 中,字符串不是一种数据类型,它们只是其他变量(确切地说是字符)的数组。您可以做的是:

strcpy(var[0], "ANS");

它将为您逐字节复制。

然而,strcpy 也存在一些缺陷。首先,目标 char 数组(在本例中为 var[0])必须足够大以包含该字符串。它不会为您检查这一点(实际上它不能),因此如果您不小心,可能会导致缓冲区溢出。此外,源必须以 NULL 结尾。

You have sort of answered your own question. You want to assign var[0][0,1,2,3] to "ANS" right? Well "ANS" is an array of characters, ans[0,1,2,3] (don't forget the null terminator). So you have to assign each one individually. In C strings aren't a data type, they are just an array of other variables (chars to be exact). What you can do instead is:

strcpy(var[0], "ANS");

Which will do the byte-by-byte copy for you.

There are some pitfalls to strcpy, however. First, the destination char array (var[0] in this case) must be large enough to contain the string. It will not check this for you (it can't, actually) so if you are not careful you can cause a buffer overflow. Also, the source must be NULL terminated.

面犯桃花 2024-09-11 06:02:00

当您编写时,

var[0][] = "ANS"

编译器会尝试将“ANS”分配给 var[0][0],该位置仅包含一个字符。

因此,您应该使用 strcpy 函数。 strcpy 将逐个字符复制。

When you write

var[0][] = "ANS"

Compiler tries to assign "ANS" to var[0][0] which is a place for only one char.

Therefore, you should use strcpy function. strcpy will copy char-by-char.

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