Why are the values of x and v[0] not equal? - C language

Asked

Viewed 73 times

0

I’m reviewing some concepts on the site : Addresses and Pointers, until I find the following code:

void func1 (int x) {
   x = 9 * x;
}

void func2 (int v[]) {
   v[0] = 9 * v[0];
}

int main (void) {
   int x, v[2];
   x    = 111; 
   func1 (x); printf ("x: %d\n", x);
   v[0] = 111; 
   func2 (v); printf ("v[0]: %d\n", v[0]);
   return 0;
}

See it working on Ideone

To my surprise the exit was:

x: 111
v[0]: 999

My doubt:

Why are x and V[0] not the same? Since they have the same value (111)

1 answer

3


Good afternoon Luiz,

This is because in function func1 (int x) you are passing the value of x, not the reference of x, so the changes of the value of x are made only within the function.

If you play a printf() within the funct1 you will see that it will give 999.

this does not occur in the case of funct2 because it is a vector, the value of v(no reference) is already the memory address of element 0 of the vector.

An example of this is when we work with strings in C, we do not use the & in the scanf() because the variable already stores the address of the first element.

Solution:

If you want to keep the same format of the function, that is, you do not want to pass as a parameter a pointer to change the value of x, you can modify your code to x receive the result of the function

Code:

#include <stdio.h>

int func1 (int x) {

   x = x * 9;    
}

void func2 (int v[]) {
   v[0] = 9 * v[0];
}

 int main (void) {

  int x, v[2];

  x = 111; 
  x = func1 (x);
  printf ("x: %d\n", x);

  v[0] = 111; 
  func2 (v); 
  printf ("v[0]: %d\n", v[0]);
  return 0;
}

Already in case you want to change the function to pass x as a parameter, it will look like this:

#include <stdio.h>

int func1 (int *x) {

  *x = *x * 9;

}

void func2 (int v[]) {

    v[0] = 9 * v[0];
}

int main (void) {
int x = 111, v[2];

func1 (&x);
printf ("x: %d\n", x);

v[0] = 111; 
func2 (v); 
printf ("v[0]: %d\n", v[0]);

return 0;
}

Where *x refers to the content of the variable x.

I don’t know if it’s clear, but I’ll edit the answer if there’s any doubt.

I hope I’ve helped,

Hugs!

  • If you want to edit your question by adding the piece of code where x passes by parameter and not value.

  • The same second I sent you edited, good!

  • Good afternoon H. Lima!! perfect the answer, has cleared up a lot of things here! thank you very much!!

  • I’m happy to help! Good luck in studies :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.