0
I have these two examples here:
example 1:
void copiaStr(char *a,char *b){
b = (char *) malloc(strlen(a));
for(int i = 0; i < strlen(a) ;i++){
b[i] = a[i];
}
}
int main(){
char *a = "alou";
char *b;
printf("%s\n",a);
copiaStr(a,b);
printf("%s\n",b);
}
example 2:
void copiaStr(char *a,char *b){
for(int i = 0; i < strlen(a) ;i++){
b[i] = a[i];
}
}
int main(){
char *a = "alou";
char *b = (char *) malloc(strlen(a));
printf("%s\n",a);
copiaStr(a,b);
printf("%s\n",b);
}
The first example does not work, gives segmentation error, as if the address allocated within the method, and assigned to b
, did not continue after the end of the method, but I passed b
as a pointer, I thought it would be a value pass per reference, why is this error occurring? And how to make b take the value of malloc()
from within the method?
The example is simple, but I think I’m having the same problem when I write list manipulation methods.
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).
– Maniero