#Making sense of pointer assignment in C

8 messages · Page 1 of 1 (latest)

ornate vale
#

Hello guys, consider the following code:

#include <stdio.h>

// Declare the function to swap two numbers
void swapping(int *num1, int *num2);

int main(void) {
    int num1, num2;

    // Get input from the user
    printf("Enter num 1: \n");
    scanf("%d", &num1);
    printf("Enter num 2: \n");
    scanf("%d", &num2);

    // Call swapping function
    swapping(&num1, &num2);

    // Print the swapped values
    printf("After swapping: num1 = %d, num2 = %d\n", num1, num2);

    return 0;
}

// Define the swapping function
void swapping(int *num1, int *num2) {
    int temp = *num1;
    *num1 = *num2;
    *num2 = temp;
}

consider this assignment :

*num1 = *num2

like here if num1 is pointing to memory address at 0x100 holding value 10 and pointer of num2 is pointing a memory address of 0x200 holding 20, this would mean 10 = 20

This doesn't make sense, right ? How should I interpret this statement then? Well, the thing is how can we think if it like a normal statement where we have something like "x = 35" for e.g

dire pulsarBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

west sierra
#

it matters to the language what side of the = sign a thing is on. because assignment always goes x <- y (to borrow R's syntax), that means that in the case of *num1 = *num2, *num1 = 20 is equivalent code (assuming *num2 contains 20). on the right side of the = sign, all variables collapse into the thing contained inside them; on the left, no collapsing is done, it just contains the result of whatever is on the right

#

also, *foo always means the same thing to me, at least conceptually: you're telling the compiler that you want foo to be interpreted as a pointer. in a declaration (int *foo;), you're declaring it so; in normal use, it's more like "try to make it so"

lament kiln
#

You passed the addresses of two int to the function. So num1 & num2 inside the function mean pointers that store some address. But *num1 helps u to get to what's stored there. Hope u hot it

ornate vale
#

yep I see, ty

dire pulsarBOT
#

@ornate vale Has your question been resolved? If so, type !solved :)

ornate vale
#

!solved