简体   繁体   中英

Assigning a string to a 2D array

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

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.

也许改用

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM