1

When I try to run the program it crashes, but it prints the numbers.Why is that?

void z(int **k)
{
    int i;
    *k=malloc(20*sizeof(int));
    for (i=0;i<20;i++)
        *k[i]=10;

}
int main()
{
    int *k,i;
    z(&k);
    for (i=0;i<20;i++)
    printf("%d\n",k);
    return 0;
}
6
  • It happens because you are printing the pointer and not the value where the pointer points to. By the way, free that memory too. Commented Jan 20, 2016 at 4:38
  • 2
    *k[i]=10; --> (*k)[i]=10;, printf("%d\n",k); --> printf("%d\n",k[i]); Commented Jan 20, 2016 at 4:40
  • @Michi I placed an asterisk before k but it still crashes. Commented Jan 20, 2016 at 4:42
  • @BLUEPIXY Thank you very much.It works now.Why should I place a parenthesis ? Commented Jan 20, 2016 at 4:44
  • It is because of the binding priority. *k[i] meant *(k[i]) Commented Jan 20, 2016 at 4:48

1 Answer 1

4

The problem is in

*k[i]=10;

By the order of precedence, it should be,

(*k)[i] = 10;

The subscripting operator has a higher precedence than the indirection operator. See Operator Prececence Rules.

Also, in the printf in main, you are printing printf("%d\n",k). This will print the base addresses of the array. If you want the value you should use

printf("%d\n",k[i]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.