C语言 在 C 中为字符数组(字符串)赋值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46865386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 10:43:25  来源:igfitidea点击:

Assigning a value to a char array (String) in C

c

提问by Ayibogan

I tried to assign a String a value in C, but for me it doesn't work... This is, what I tried to do:

我试图在 C 中为 String 分配一个值,但对我来说它不起作用......这就是我试图做的:

#include <stdio.h>
#include <string.h>
int main()
{
char k[25];
k == "Dennis"
printf("My Name is %s", k);
}

Sample Output would be: My Name is Dennis

示例输出将是:我的名字是丹尼斯

However, I receive the a warning: warning: comparison of distinct pointer types lacks a cast k == "Dennis";

但是,我收到警告:警告:不同指针类型的比较缺少强制转换 k == "Dennis";

I tried to find a solution on this website, but could not find one, where it was the same error with assigning a value to a char array (a string) in C

我试图在这个网站上找到一个解决方案,但找不到一个,在 C 中为字符数组(字符串)赋值时出现同样的错误

Also tried initializing my char as

还尝试将我的字符初始化为

  char *k[25];

still didn't work...

还是没用...

回答by usr

  1. You are indeed doing a comparison here: k == "Dennis". So the compiler correctly warns you.

  2. You probably meant k = "Dennis";(fixed the missing semi-colon there). But that won't work either. Because in C arrays are not modifiable lvalues.

  1. 您确实在这里进行了比较:k == "Dennis"。所以编译器会正确警告你。

  2. 您可能的意思是k = "Dennis";(在那里修复了丢失的分号)。但这也行不通。因为在 C 数组中是不可修改的左值。

So you can either initializethe array:

所以你可以初始化数组:

char k[25] = "Dennis";

or, use strcpyto copy:

或者,用于strcpy复制:

strcpy(k, "Dennis");


If you actually have no need for an array, you can simply use a pointer that points to the string literal. The following is valid:

如果您实际上不需要array,则可以简单地使用指向字符串文字的指针。以下内容有效:

char *k;
k = "Dennis";
printf("My Name is %s", k);