assigning char pointer to char and char array vari

2019-04-14 16:02发布

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.

标签: c pointers char
5条回答
beautiful°
2楼-- · 2019-04-14 16:15

When you say

char a[10];

'a' is actually

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.

So

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

are allowed. But

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

is not allowed.

查看更多
\"骚年 ilove
3楼-- · 2019-04-14 16:24

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.

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

查看更多
家丑人穷心不美
4楼-- · 2019-04-14 16:28

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

查看更多
三岁会撩人
5楼-- · 2019-04-14 16:35
char a;
char b[]="asdf";
a=b;

Here you are assigning address of array b to a which is of char type. 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. This is legal but its of no use.

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

查看更多
Animai°情兽
6楼-- · 2019-04-14 16:37

Both are not ok.

Maybe you were attempting ,

char *a;
char b[]="asdf";
a=b;
查看更多
登录 后发表回答