Reputation: 25
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
Upvotes: 1
Views: 93
Reputation: 311
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
Upvotes: 0
Reputation: 129
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.
Upvotes: 1
Reputation: 2513
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
.
Upvotes: 3