The print comes out weird after changing the value from C to pointer.

Asked 2 years ago, Updated 2 years ago, 58 views

#include <stdio.h>
#include <string.h>

int main(void) {
    char pA[10] = "seoul";
    char *pB = pA;
    *pB = "busan";
    printf("%s", pB);
    printf("%s", pA);
}  

After entering the code like this, the output value comes out like 8eoul8eoul. Why is that?

c pointer

2022-09-22 19:32

2 Answers

#include <stdio.h>
#include <string.h>

int main(void) {
    char pA[10] = "seoul";
    pA[5] = NULL;

    printf("\n");

    char *pB = pA;
    //*pB = "busan";

    printf("%s\n", pA);
    printf("%s\n", pB);
}  

Add NULL and spin it Uncomment the PB and compile it If you annotate and compile it, you can check how the memory address changes.


2022-09-22 19:32

*pB = "busan"; // compilation error

There must have been a compilation error on the above line.

pB = (char*)"busan";

Fix it like this and try it.


2022-09-22 19:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.