Reputation: 63
i'm a little bit confused about the behavioral of this code,
#include <stdio.h>
#include <stdlib.h>
char* foo(){
char* arr = (char*)malloc(sizeof(char)*100);
return arr;
}
void foo1(char* myArr){
char* arr = (char*)malloc(sizeof(char)*100);
myArr = arr;
}
int main(){
char* myArr;
foo1(myArr);
myArr[23] = 'a';
printf("%c", myArr[23]);
return (0);
}
When i call myArr = foo()
, it works just fine and the value of an allocated memory address will assigned to myArr
and i have an allocated memory segment with no errors. On the other hand, when i call the function foo1(myArr)
it has to pass myArr
to the function, it's a pointer to a segment so any changes with this pointers will affect the memory segment, (for example if i want to swap two string values, i can simply swap the pointers), but i will get a segmentation fault error
, why? because myArr is not myArr in main
function? is that true?!!
Upvotes: 0
Views: 69
Reputation: 126536
Arguments in C are always call-by-value -- the argument gets a copy of what the caller passes and is a new variable, so if the function changes the value of the argument it does not affect the value of whatever was passed in. So when you call
foo1(myArr);
the value of myArr
will not change, even if foo1 assigns a different value to it.
Upvotes: 1
Reputation: 182883
You call two different variables myArr
, which is probably confusing you. Changes to the myArr
in foo1
have no affect on the myArr
in main
just because they have the same name. You pass the value of the myArr
in main
to foo1
, but nothing is returned.
void foo1(char* myArr){
char* arr = (char*)malloc(sizeof(char)*100);
myArr = arr;
}
This is no different conceptually from:
void foo1(int j) {
int q = 2;
j = q;
}
Just as foo1(3)
wouldn't somehow turn that 3
into a 2
, foo1(myArr)
doesn't change the value of myArr
. That myArr
is a pointer doesn't change its semantics -- C is pass by value, period. So only myArr
's value is passed to the function.
char* myArr;
foo1(myArr);
Notice that myArr
is not assigned a value here, so you are passing foo1
the value of a pointer to nothing in particular. There is nothing useful foo1
can do with that value.
You probably want:
void foo1(char** myArrPtr){
char* arr = (char*)malloc(sizeof(char)*100);
*myArrPtr = arr;
}
and
char* myArr;
foo1(&myArr);
That way, the function gets a pointer to myArr
and then modifies the thing that pointer points to, which is the myArr
in main
.
Upvotes: 3