JuMoGar
JuMoGar

Reputation: 1760

C - Local function variable chages value of Scope (global) variable Error behavior

I have a global variable called: char clientes_dni[]. I am calling (from the main) a function like: comprobarExistenciaDNI(clientes_dni). My function comprobarExistenciaDNI is:

bool comprobarExistenciaDNI(char DNI[]) {
    /// Change to lower DNI last word
    DNI[8] = tolower(DNI[8]);
    return (true);
}

If my var has the value '11111111J', after function the value is '11111111j'. I am not working with global variable, only with the local variable so... Why value of clientes_dni is changed?

Thank you.

Upvotes: 1

Views: 56

Answers (3)

Carlos M.
Carlos M.

Reputation: 147

I think the problem is that DNI is an array (a pointer) so you are actually modifying the contents of the array when you say

DNI[8] = tolower(DNI[8]);

It's like when you send a variable by reference to a function.

Do you have experience with pointers?

Edit 1:

I'll give you a quick spoiler. A pointer is the value of a memory address. Like i said, an array is a pointer, this one "points" to the first element of the array in memory (the elements are one next to each other) so when you send clientes_dni you are sending the location of the first element to the comprobarExistenciaDNI function. The function then modifies the value (the contents) of that memory address. That's why it gets modified in the main scope, because you modified the content of the memory address.

It is different when you send a variable of any other data type, you are sending a copy of the variable instead of the variable itself.

Upvotes: 3

bipll
bipll

Reputation: 11950

Your local variable is of pointer type and it refers to a global string. 'Array' arguments of functions are not allocated and deep-copied but rather bound to addresses.

Upvotes: 1

grovkin
grovkin

Reputation: 158

Arrays are passed by the address of the 1st element. In most use cases (there are few exceptions like sizeof operator), the name of an array (let's say A) is synonymous with &A[0]. structs are passed by value, if that's what you are looking to do (wrap the array in struct).

Upvotes: 1

Related Questions