简体   繁体   中英

i am trying to copy a string in c using pointers

char ch0[10] = "hello";
char ch1[10];

void main(){
    clrscr();
    char *pt0 = ch0;
    char *pt1 = ch1;
    puts(pt0);

    while(*pt0 != '\0')
    {
        *pt1++ = *pt0++;
    }
    *pt1 = '\0';

    printf("value of ch1 =");
    for(int i = 0; i < sizeof(ch1); i++){
        printf("%c",ch1[i]); // prints value correctly
    }

    putchar('\n');
    printf("pointer pt1 value = %c",*pt1); // gives garbage value
    getch();
}

Pointer pt1 value is not accessible however the ch1 is pointing to the correct value.

How to access pt1?

I am not good in pointers can any only explain me the working scenario

output:
hello
value of ch1 =hello
pointer pt1 value= \\garbage value

Looks to me like you just need to reset pt1 . After your copy loop, it's pointing to the end of the string in the ch1 array.

So, after the line:

*pt1='\0';

pt1 is pointing to the end of the string in ch1 . So, to print it out, you need to reset it back to ch1 .

There is a typo in your code:

char *pt0 =ch;

should perhaps be:

char *pt0 =ch0;

Your compiler should notice that but maybe it would be better to correct it here also for consistency. Apart from this the bruceg's answer is right.

In your code, you are incrementing the pointer ptr1 and then atlast your assigning value "NULL" . So no longer the ptr1 holds the ch1 string.

For better understanding, you can print the addresses of both ch1 and ptr1 . You will understand much better

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM