将字符串分配给二维数组
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许改为使用,
Perhaps instead using,
你已经回答了你自己的问题。您想将 var[0][0,1,2,3] 分配给“ANS”,对吗?那么“ANS”是一个字符数组,ans[0,1,2,3](不要忘记空终止符)。所以你必须单独分配每一项。在 C 中,字符串不是一种数据类型,它们只是其他变量(确切地说是字符)的数组。您可以做的是:
它将为您逐字节复制。
然而,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:
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.
当您编写时,
编译器会尝试将“ANS”分配给 var[0][0],该位置仅包含一个字符。
因此,您应该使用 strcpy 函数。 strcpy 将逐个字符复制。
When you write
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.