简体   繁体   English

我正在尝试使用指针在c中复制字符串

[英]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. 指针pt1值不可访问,但是ch1指向正确的值。

How to access pt1? 如何访问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 . 在我看来,您只需要重置pt1 After your copy loop, it's pointing to the end of the string in the ch1 array. 复制循环之后,它指向ch1数组中字符串的结尾。

So, after the line: 因此,在行之后:

*pt1='\0';

pt1 is pointing to the end of the string in ch1 . pt1指向ch1字符串的结尾。 So, to print it out, you need to reset it back to ch1 . 因此,要打印出来,您需要将其重置回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" . 在您的代码中,您要递增指针ptr1 ,最后分配赋值“ NULL” So no longer the ptr1 holds the ch1 string. 因此, ptr1不再保存ch1字符串。

For better understanding, you can print the addresses of both ch1 and ptr1 . 为了更好地理解,您可以同时打印ch1ptr1的地址。 You will understand much better 您会更好地了解

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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