3

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 ?

lurker
  • 56,987
  • 9
  • 69
  • 103
user2528042
  • 419
  • 2
  • 6
  • 12

3 Answers3

3

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.

Sergey L.
  • 21,822
  • 5
  • 49
  • 75
  • The type of `b - a` is a `ptrdiff_t`, which is guaranteed to be a signed int. C compilers do not often give warnings when you assign a signed int to a signed int variable. – Lundin Sep 06 '13 at 13:39
  • @Lundin No they do not, but they generally do when more then one pointer value appears in the same arithmetic expression. – Sergey L. Sep 06 '13 at 13:40
  • Yeah your completely right . Just forgot how C works ! Basics isnt it ..shouldnt have asked :P – user2528042 Sep 06 '13 at 13:41
  • I don't believe I have ever seen a compiler give a warning for that. `gcc -std=c99 -pedantic -Wall -Wextra` gives no errors for this code. – Lundin Sep 06 '13 at 13:43
2
  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";
alk
  • 69,737
  • 10
  • 105
  • 255
Gangadhar
  • 10,248
  • 3
  • 31
  • 50
  • 1
    It should be noted that subtracting pointers to two objects not contained in one array does not have behavior defined by the C standard. – Eric Postpischil Sep 06 '13 at 14:19
0

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()

MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • what you said about addresses is right but C doesnt have objects ! may be its a wrong terminology , use pointers or references – user2528042 Sep 06 '13 at 13:50