简体   繁体   English

二维数组初始化

[英]Two dimensional array initialization

i have created an two dimensional array like this: 我创建了一个像这样的二维数组:

char string_y2m[2][8];

Then I just used memset() for initialize it by 0: 然后我只是使用memset()将其初始化为0:

memset(&string_y2m, 0, sizeof(string_y2m));

Now I have to assign it some value but it's not working. 现在,我必须为其分配一些值,但是它无法正常工作。 I have assigned it like this: 我已将其分配为:

string_y2m[2][8] = {"2011-1","2011-01"};

It's not working, same thing if I do at declaration itself, it works. 这是行不通的,如果我在声明本身上做同样的事情,它会工作。

You cannot assign strings like that in C, when the target is a character array and you're not also declaring it. 当目标是一个字符数组并且没有声明时,就不能在C中分配类似的字符串。

In C, you need to use strcpy() to copy the string into the array, paying a lot of attention to the buffer sizes: 在C语言中,您需要使用strcpy()将字符串复制到数组中,并特别注意缓冲区的大小:

strcpy(string_y2m[0], "2011-1");
strcpy(string_y2m[1], "2011-01");

Or use snprintf() if you have it: 或使用snprintf()如果有):

snprintf(string_y2m[0], sizeof string_y2m[0], "%s", "2011-1");
snprintf(string_y2m[1], sizeof string_y2m[1], "%s", "2011-01");

Also, there's no need to clear the space before writing the string there, since writing the string will set the characters to the required values. 另外,在写入字符串之前无需清除空格,因为写入字符串会将字符设置为所需的值。

Just don't use assignment but initialize the array correctly from the start: 只是不使用赋值,而是从一开始就正确初始化数组:

char string_y2m[2][8] = {"2011-1","2011-01"};

This will initialize all characters that are not initialized explicitly to 0 . 这会将所有未显式初始化为0字符初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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