C语言 c - 如何在c中将char *转换为char []

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2074116/
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 04:09:55  来源:igfitidea点击:

how to convert from char* to char[] in c

ctype-conversion

提问by Bassel Shawi

here is a code sample

这是一个代码示例

void something()
{
   char c[100];
   scanf("%s",c);
   char c2[100]=c;
}

my problem is when i do this assignment an error says that i can't assign

我的问题是当我做这个任务时,错误说我不能分配

char * "c"  to char[] "c2";

how can i achieve this assignment?

我怎样才能完成这项任务?

回答by John Bode

You'll have to use strcpy()(or similar):

您必须使用strcpy()(或类似的):

...  
char c2[100];
strcpy(c2, c);

You can't assign arrays using the =operator.

您不能使用=运算符分配数组。

回答by Fred Larson

You need to use strcpy()

你需要使用 strcpy()

char c2[100];
strcpy(c2, c);

回答by aiGuru

Better practice would be to use strncpy(c2, c, 100) to avoid buffer overflow, and of course limit the data entry too with something like scanf("%99s", c);

更好的做法是使用 strncpy(c2, c, 100) 来避免缓冲区溢出,当然也可以使用 scanf("%99s", c); 之类的方法限制数据输入。

回答by Chris Dodd

char []is not a valid value type in C (its only a valid declaration type), so you can't actualy do anything with char []types. All you can do is convert them to something else (usually char *) and do something with that.

char []在 C 中不是一个有效的值类型(它只是一个有效的声明类型),所以你实际上不能对char []类型做任何事情。您所能做的就是将它们转换为其他东西(通常char *)并对其进行处理。

So if you wany to actually do something with the data in the array, you need to use some function or operation that takes a char *and derefences it. Obvious choices for your example are strcpyor memcpy

因此,如果您想对数组中的数据进行实际操作,则需要使用一些函数或操作来获取 achar *并取消对它的引用。您的示例的明显选择是strcpymemcpy