tags:

views:

66

answers:

2
#include <stdio.h>
#include <stdlib.h>
char *color[] =
{
    /*0*/"red||bluegreen",
    /*1*/"blue",
    /*2*/"green",
         "\0"
};

int fun1(char * str1)
{
    int c = 0;
    while(1)
    {
        if(str1[c] == '|' && str1[c+1] == '|')
            return c;
        c++;    
    }
    return 0;    
}


1. int main()
2. {
3.  int ret=0, offset=0;
4.  ret = fun1(color[offset]);
5   offset += ret;
6   ret = fun1(color[offset]);

7   return 0;
   }

In the above code snippet in main() at line 6 the argument to fun1() is color[offset] = NULL Why is color[offset] = NULL after the operation offset += ret. Please clarify

Thanks

+3  A: 

The first call to fun1 here ret = fun1(color[offset]); returns 3 as color[0][3] and color[0][4] are both |.

Then you add ret to offset making it 3.

In the next call to fun1 you pass it color[offset] which is color[3] which is "\0", note that this is not NULL its a string literal containing only the nul character.

To clarify:

char *str = NULL;  // str is null pointer.
char *str = 0;     // same as above.

char *str = "\0";  // str is pointer to an empty string literal.
char *str = "";    // same as above.
codaddict
A: 

When you add to offset, it is going to advance by the number equal to ret. So, it advances 3 places, which brings it to an offset of 3, so color[offset] = color[3] = "\0". When you then call fun1, it will loop forever because there are no | characters. This continues until something terrible and undefined happens.

JoshD