C语言 将 char 指针分配给 char 和 char 数组变量

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

assigning char pointer to char and char array variable

cpointerschar

提问by Majid alDosari

Why is the following ok?

为什么下面没问题?

    char *a;
    char b[]="asdf";
    a=b;

But the following is not?

但是下面是不是?

    char a[10];
    char b[]="asdf";
    a=b;

The above gives error: incompatible types in assignment.

以上给出了错误:赋值中的类型不兼容。

回答by Barath Ravikumar

Both are not ok.

两个都不行。

Maybe you were attempting ,

也许你正在尝试,

char *a;
char b[]="asdf";
a=b;

回答by rashok

char a;
char b[]="asdf";
a=b;

Here you are assigning address of array bto awhich is of chartype. Size of address will be 4 bytes (8 bytes in 64 bit m/c) which you are assigning to 1 byte charvariable aso the values will get truncated. This is legal but its of no use.

在这里,你正在分配数组的地址ba这是char类型。地址的大小将为 4 字节(64 位 m/c 中的 8 字节),您将其分配给 1 字节char变量,a因此值将被截断。这是合法的,但没有用。

I think you are actually trying to assign first character of barray to a. In that case do a = b[0].

我认为您实际上是在尝试将b数组的第一个字符分配给a. 在那种情况下做a = b[0]

回答by wats nothin

The value of an array evaluates to the address of the first element within the array. So basically, it's a constant value. That's why when you try to do a=b in the second example, you're trying to do something similar to 2=7, only you have two addresses instead of 2 integers.

数组的值计算为数组中第一个元素的地址。所以基本上,它是一个常数值。这就是为什么当您尝试在第二个示例中执行 a=b 时,您正在尝试执行类似于 2=7 的操作,只有您有两个地址而不是两个整数。

Now it makes sense that the first example would work, since assigning an address to a pointer is a valid operation.

现在第一个示例可以工作是有道理的,因为将地址分配给指针是一个有效的操作。

回答by Marlon Louis

You need to include the below header for string library.

您需要为字符串库包含以下标头。

#include <string.h>

#include <string.h>

Using strcpy(strX, strY);will copy string Y into string X, given there is enough space.

如果strcpy(strX, strY);有足够的空间,使用会将字符串 Y 复制到字符串 X 中。

回答by Kishore

When you say

当你说

char a[10];

'a' is actually

'a' 实际上是

char * const a = malloc(sizeof(char) * 10); // remember to free it, can use alloca() instead

and 'a' is initialized to point to 10 * sizeof(char) of allocated memory.

并且 'a' 被初始化为指向已分配内存的 10 * sizeof(char)。

So

所以

a[1] = 't';
*(a + 1) = 't';

are allowed. But

被允许。但

char *b = "some string";
a = b;

is not allowed.

不被允许。

回答by Digvijay Rathore

Please use strcpy_s function of c++, it is having a syntax of &dest,*source it might help.

请使用 c++ 的 strcpy_s 函数,它的语法为 &dest,*source 可能会有所帮助。