This question already has answers here:
Proper way to copy C-strings
                                
                                    (4个答案)
                                
                        
                                5年前关闭。
            
                    
我创建了一个非常简单的代码,但是它不起作用!我只想创建一个包含字符串的数组。但是,这些字符串必须不带字符字符方法。换一种说法:

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
    char wstr[20][10];
    int i;
    for (i=0;i<20;i++)
            wstr[i]='BA';
    return 0;
}


但编译器向我显示警告和错误:

[Error] incompatible types when assigning to type 'char[10]' from type 'int'
[Warning] multi-character character constant [-Wmultichar]


我该怎么办?

最佳答案

for (i=0;i<20;i++)
            strcpy(wstr[i], "BA");


单引号用于单个字符;字符串文字使用双引号。
strcpy()调用可确保您以后能够修改值,
因为修改字符串文字本身是未定义的行为。

09-25 16:26
查看更多