3

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.

1
  • 2
    I find it unlikely that you aren't at least getting some warnings with your first example. Could you post the complete output from your compiler? Commented Mar 15, 2013 at 3:22

4 Answers 4

1

Both are not ok.

Maybe you were attempting ,

char *a;
char b[]="asdf";
a=b;
Sign up to request clarification or add additional context in comments.

3 Comments

Actually, the first one is legal, but it's probably not what's intended.
@CongXu , yes ,these beginneres must know ,all that compiles , is not right !!
It can be "right". For example if 'a' were a pointer to int it would be an acceptable practice. The fact that it compiles without a warning likely indicates that there is rationale to allow the assignment.
0
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].

Comments

0

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.

Comments

-1

You need to include the below header for string library.

#include <string.h>

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

1 Comment

strcpy() does not check that there is enough space available, in fact it has no way to do so. You can use strncpy() to control that you don't buffer overflow, but you may have to insert the final null byte manually.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.