0

I can't understand this code segment. What I think I know is that when I pass "abc" then x becomes a pointer to first element in string is this correct? and why is it giving me infinite loop?

Here's my code:

void foo1(char* x)
{
    if (!x)
        return;
    printf("%c ",*x);
    foo1(++x);
}

int main()
{
    foo1("abc");
    return 0;
}
michalsrb
  • 4,703
  • 1
  • 18
  • 35
Zeyad Ibrahim
  • 13
  • 1
  • 7
  • `if (!x)`->`if (!*x)` or a bit more readable: `if (!(*x))` or even more readable `if (x[0] == 0)` – Jabberwocky Jan 17 '18 at 11:23
  • so what is the problem? why the compiler is giving me infinite loop? can u explain the mechanism? – Zeyad Ibrahim Jan 17 '18 at 11:25
  • Relevant: [What is the difference between NULL, '\0' and 0](https://stackoverflow.com/q/1296843/694733) – user694733 Jan 17 '18 at 11:43
  • Just in passing, there's no need to assign back to `x` (i.e. `++x`), as it's not used again in the same scope. Just recurse with `foo1(x+1)` instead (remember that each invocation of `foo1()` gets its own value of `x`, that's unrelated to any other `x` in the program). – Toby Speight Jan 17 '18 at 12:04

4 Answers4

2

You stop iterating when the pointer becomes null. What you actually want is to stop iterating when you get to the \0 character (ie the end of the string):

int main()
{
  foo1("abc");

  return 0;
}

void foo1(char* x)
{
  if (*x == 0)
      return;

  printf("%c ",*x);
  foo1(++x);
}

Because you're iterating on the pointer value, rather than the item pointed to, you'll basically start to iterate over the process address space, starting from the location of the string. Chances are you'll run out of stack space before you get to an invalid address that causes a segmentation fault!

Sean
  • 60,939
  • 11
  • 97
  • 136
0

The problem is in your terminating condition

if (!x)
    return;

Your pointer x never becomes 0 (or NULL). So it never terminates.

Raman
  • 2,735
  • 1
  • 26
  • 46
0

This test is wrong:

if (!x)

your are simply testing if x is 0 and this never happens and therefore the base case never happens.

Instead you need to check if x points to a NUL character (strings are terminated by a NUL character):

if (x[0] == 0) 
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
0

you need check not only pointer value but end of string also. You code if(*x) checks only pointer value. You need check string element value also if(!x && !(*x))