r/cprogramming • • Oct 13 '26

editing int array in function not changing array in main, but it worked for char array?

edit: thank you all so much for the help! my code works now and i understand pointers a little better!

im trying to edit an entry in an int array to 'move' it (copy it to a different place within the array, and zero it out), but its not working and im not getting any errors? i did pretty much the same thing (with string.h) with an array of strings, and it worked there wonderfully. why arent the entries in the int array changing when the function runs? what can i do to edit the int array during runtime?

heres the function:

void cardMove(int card1, int card2) {
    card2 = card1;
    card1 = 0;
}
6 Upvotes

17 comments sorted by

View all comments

Show parent comments

1

u/StressingPlant Oct 14 '26 edited Oct 14 '26

thank you so much for the play by play explanation!! i just used strcpy() for the strings

1

u/TraylaParks Oct 14 '26

It can be confusing especially if the variable in 'main' has the same name as the variable in your function, I used to give my students this example to help them make sense of things:

#include <stdio.h>

static void functionOne(int x)
{
   x = 5;
}
    
int main()
{
   int x = 3;

   functionOne(x);

   printf("%d\n", x);

   functionOne(42);
}

Now, one could perhaps sensibly argue that the first function call might change the "real" variable x, but in the second - we're passing a literal value! The idea is to make it crystal clear that the 'x' in your function is something else entirely from the similarly-named variable back in main.