Learner
Learner

Reputation: 1644

Why a String variable can not be assigned to another string variable in C?

Why in the below written code we can not assign strA to strB and as the pointer pA holds address of pointer pB then address should have been copied on assignment of pA to pB and strB should have contain the value same as strB.

#include <stdio.h>
char strA[80] = "A string to be used for demonstration purposes";
char strB[80];
int main(void)
{
    char *pA; /* a pointer to type character */
    char *pB; /* another pointer to type character */
    puts(strA); /* show string A */
    pA = strA; /* point pA at string A */
    puts(pA); /* show what pA is pointing to */
    pB = strB; /* point pB at string B */
    putchar('\n'); /* move down one line on the screen */
    pB=pA;
    strB=strA;
    puts(strB); /* show strB on screen */
    puts(strA);

    return 0;
}

Upvotes: 0

Views: 1901

Answers (2)

Nicolas Floquet
Nicolas Floquet

Reputation: 434

When you write:

char strB[80];

strB is not a pointer but a constant pointer. It means that you can't change the address pointed by strB, and thus

strB=strA;

won't do anything.

Upvotes: 2

mac
mac

Reputation: 5647

You can't assign arrays in C (strB=strA). You must use strcpy or memcpy to transfer contents of one array/pointer to an array.

Upvotes: 4

Related Questions