0

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;
}
4
  • Changed the tag from C++ to C, as it seems you are specifically asking a C question. Commented Feb 23, 2012 at 11:56
  • Is this homework? Commented Feb 23, 2012 at 11:56
  • 4
    strA and strB aren't string variables. there is no such thing as string variable in C. they are arrays. an array can't be assigned to another array. Commented Feb 23, 2012 at 11:59
  • 1
    Your question is a FAQ, c-faq.com/charstring/assign.html, voting to close. Commented Feb 23, 2012 at 12:18

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

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.