Kunal Agarwal
Kunal Agarwal

Reputation: 23

How does a char pointer differ from an int pointer in the below code?

1)
  int main()
  {
   int *j,i=0;
   int A[5]={0,1,2,3,4};
   int B[3]={6,7,8};
   int *s1=A,*s2=B;
   while(*s1++ = *s2++)
   {
       for(i=0; i<5; i++)
          printf("%d ", A[i]);
   }
 }


2)
  int main()
  {
     char str1[] = "India";
     char str2[] = "BIX";
     char *s1 = str1, *s2=str2;
     while(*s1++ = *s2++)
        printf("%s ", str1);
   }

The second code works fine whereas the first code results in some error(maybe segmentation fault). But how is the pointer variable s2 in program 2 working fine (i.e till the end of the string) but not in program 1, where its running infinitely.... Also, in the second program, won't the s2 variable get incremented beyond the length of the array?

Upvotes: 0

Views: 75

Answers (3)

Nicolas Buquet
Nicolas Buquet

Reputation: 3955

Joachim gave a good explanation about String terminal character \0 in C language.

Another thing to be aware of when working with pointer is pointer arithmetic.

Arithmetic unit for pointer is the size of the entity pointed.

With a char * pointer named charPtr, on system where char are stored on 1 byte, doing charPtr++ will increase the value in charPtr by *1 (1 byte) to make it ready to point to the next char in memory.

With a int * pointer named intPtr, on system where int are stored on 4 bytes, doing intPtr++ will increase the value in intPtr by 4 (4 bytes) to make it ready to point to the next int in memory.

Upvotes: 0

PlusInfosys
PlusInfosys

Reputation: 3446

In str2, You have assigned String. Which means there will be end Of String('\0' or NULL) due to which when you will increment Str2 and it will reach to end of string, It will return null and hence your loop will break.

And with integer pointer, there is no end of string. thats why its going to infinite loop.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409166

The thing with strings in C is that they have a special character that marks the end of the string. It's the '\0' character. This special character has the value zero.

In the second program the arrays you have include the terminator character, and since it is zero it is treated as "false" when used in a boolean expression (like the condition in your while loop). That means your loop in the second program will copy characters up to and including the terminator character, but since that is "false" the loop will then end.

In the first program there is no such terminator, and the loop will continue and go out of bounds until it just randomly happen to find a zero in the memory you're copying from. This leads to undefined behavior which is a common cause of crashes.

So the difference isn't in how pointers are handled, but in the data. If you add a zero at the end of the source array in the first program (B) then it will also work well.

Upvotes: 7

Related Questions