Reputation: 437
Well , I was actually looking at strcmp() , was confused about its working . Anyways I wrote this code
#include <stdio.h>
main()
{
char a[5] = "ggod";
char b[5] = "ggod";
int c = 0;
c = b - a;
printf("%d value", c);
}
and I get the output as
16
Can anyone explain Why is it 16
?
Upvotes: 3
Views: 18012
Reputation: 10516
c = b - a;
This is pointer arithmetic. The array names it self points to starting address of array. c
hold the difference between two locations which are pointed by b
and a
.
When you print those values with %p
you will get to know in your case
if you print the values looks like this a==0x7fff042f3710 b==0x7fff042f3720
c= b-a ==>c=0x7fff042f3720-0x7fff042f3710=>c=0x10 //indecimal the value is 16
Try printing those
printf("%p %p\n",a,b);
c=b-a;
if you change size of array difference would be changed
char a[120]="ggod";
char b[5]="ggod";
Upvotes: 2
Reputation: 43518
b
is an array object
a
is also an array object
an array object is a static address to an array.
so b-a
is adifference between 2 addresses and not between the 2 strings "ggod"-"ggod"
If you want to compare between 2 string you can use strcmp()
strcmp()
will return 0 if the 2 strings are the same and non 0 value if the 2 strings are different
here after an example of using strcmp()
Upvotes: 0
Reputation: 22542
What you have subtracted there are not two strings, but two char *
. c
holds the memory address difference between a
and b
. This can be pretty much anything arbitrary. Here it just means that you have 16 bytes space between the start of the first string and the start of the second one on your stack.
Upvotes: 3