简体   繁体   English

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

[英]assigning char pointer to char and char array variable

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. 上面给出了错误:分配中的类型不兼容。

Both are not ok. 两者都不行。

Maybe you were attempting , 也许你在尝试,

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

Here you are assigning address of array b to a which is of char type. 在这里,你正在分配阵列的地址ba它是char类型。 Size of address will be 4 bytes (8 bytes in 64 bit m/c) which you are assigning to 1 byte char variable a so the values will get truncated. 地址的大小为4个字节(64位m / c中为8个字节),您将其分配给1个字节的char变量a因此值将被截断。 This is legal but its of no use. 这是合法的,但没有用。

I think you are actually trying to assign first character of b array to a . 我认为您实际上是在尝试将b数组的第一个字符分配给a In that case do a = b[0] . 在这种情况下, a = b[0]

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. 不被允许。

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的操作的原因,只有两个地址而不是2个整数。

Now it makes sense that the first example would work, since assigning an address to a pointer is a valid operation. 现在有意义的是第一个示例可以工作,因为将地址分配给指针是有效的操作。

You need to include the below header for string library. 您需要在字符串库中包含以下标头。

#include <string.h>

Using strcpy(strX, strY); 使用strcpy(strX, strY); will copy string Y into string X, given there is enough space. 如果有足够的空间,将把字符串Y复制到字符串X。

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

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

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