0

Please help me in understanding the below code, my expected output is "50".I'm able to get this output when I return pointer "s" from function "f" and in main I need to make this changes s= f(s,i).

void f(char *s,int i)
{
    s = (char*)malloc (20 *sizeof(char));
    s[i++]=50;
    s[i++]=53;
    return;
}

int main()
{
    int i = 10;
    char *s = NULL;
    f(s,i);
    printf(" s[%d]= %u \n",i,s[i]);
    free(s);
    return 0;
}
mark
  • 27
  • 2

1 Answers1

1

You don't pass s by reference.

void f(char **s,int i)
{
    *s        = malloc(20 * sizeof(char));
    (*s)[i++] = 50;
    (*s)[i++] = 53;
}

int main()
{
    int i   = 10;
    char *s = NULL;
    f(&s,i);
    printf(" s[%d]= %u \n", i, s[i]);
    free(s);

    return 0;
}

The problem is that in your case, after you return from f(s, i);, in main() the variable s is unchanged and therefore still NULL. The crash then occurs in the printf(..., s[i]); call. In particular note that free(s) will not crash because free can also be passed NULL.

Community
  • 1
  • 1
cutsoy
  • 10,127
  • 4
  • 40
  • 57
  • Thank you very much. Appreciate your quick response. – mark Mar 17 '17 at 19:04
  • Can I ask one more question?? – mark Mar 17 '17 at 19:05
  • Only if it starts with a vowel. – cutsoy Mar 17 '17 at 19:09
  • char * t(char *s1) { char *t = "pqrs"; s1 = "fdsa"; return t ; } int main() { char *s = "abcde"; s =t(s); printf("%s \n",s); return 0; } output is pqrs : How can we return local pointer?? – mark Mar 17 '17 at 19:14
  • Pointers hold the address of memory location. Initially `pointer s` in `main` function have address of stating position of string `"abcd"`. Function `t` returns the address of pointer `t`, it replaces previous value of `s` in `main` function. Since pointer `t` is local to function `t` you can't access it outside of its scope. But in your code you make `s` in `main` to point to pointer `t`'s value, which is possible as local variables are stored in memory and memory is not restricted by scope. If somehow you can do that you will get restricted access error. – svtag Mar 17 '17 at 20:29