0

I have a little confusion. Please look into following program:

#include<stdio.h>
void display (int *j, int *k);

int main()
{
    int num1[]={1,2,3,4,5};
    int num2[5];
    int i;
    display (num1,num2);
    for (i=0;i<=4;i++)
        printf("%d,", num2[i]);
    return 0;
}

void display (int *j, int *k)
{
    int l;  
    for (l=0;l<=4;l++)
    {
        k=j;
        printf("%d,", *k);
        j++;
        k++;        
    }

}

In this printf("%d,", num2[i]); is not giving the array. But it works when we put *k=*j; in the function. Can you please explain why ? Thanks.

1
  • 4
    To whomever is trying to edit this post: fixing indention is fine, changing the coding style to suit your own personal preference is not, that is to be regarded as changing the meaning of the code. Commented Nov 23, 2012 at 12:11

4 Answers 4

1

k=j assigns the pointer k to the value (address pointed to) of pointer j. This toggles which array (num1 or num2) k points to but doesn't change the value of any array element.

*k=*j sets the array element that k points to to the value of the array element j points to.

Sign up to request clarification or add additional context in comments.

Comments

0

Because you have not initialized the array num2 nor copy it from num1.

Comments

0

*k = *j copies the content of the "cell" j points to to the cell k points to. On the contrary, k = j makes k point to where j points. If you think about this, k = j is wrong, as you do not alter the content of your arrays, but rather just change the local variable k. Hence in your example, the print statement inside display does, in fact, not print num2, but num1 (as at the point of the print statement, k points to the same location as j does, which is an element of num1).

Comments

0

The statement k = j; which means "assign the value stored in j as the value of k", merely copy the value stored in j to k. It does nothing on the arrays, just the pointer k points to the address pointed to by j. The assignment and increments effects only local variable j and k, nothing else.

When you write *k = *j;, it essentially means "assign the content of address j to address k", which does the copying, and incrementing j and k points them to the next array element.

1 Comment

Thank you all, I need to more involve beacause I can't understand fully your answers. Thanks.

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.