1

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.

1
  • the posted code is passing a pointer to the global array 'clientes_dni, so when calling tolower()` the result is being assigned to that global variable. Commented Mar 11, 2018 at 20:23

3 Answers 3

3

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.

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

1 Comment

Thank you! I'll keep it in mind. No, I'm not. Tomorrow I'll start with pointers, I am learning C.
1

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).

Comments

1

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.

Comments

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.