1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void doSth(char *a)
{
    char *b,*c;
    b = malloc(2*sizeof(char));
    b[0]='a';
    b[1]='\0';

    a = malloc(2*sizeof(char));
    c = malloc(2*sizeof(char));
    strcpy(a,b);
    strcpy(c,b);

    printf("c:%s\n",c);
    free(c);
    free(b);
}


int main()
{
    char *myString;

    doSth(myString);

    printf("%s\n",myString);

    free(myString);
    return 0;
}

This program outputs only "c:a". Why can't I copy b to a? According to the debugger, the variable "a" remains empty in every line.

2
  • 3
    Hint: C has pass by value semantics for function arguments. Commented Mar 21, 2015 at 23:06
  • always check the returned value from malloc (and family) (!=NULL) to assure the operation was successful Commented Mar 21, 2015 at 23:15

1 Answer 1

4

By doing a = malloc(2*sizeof(char)); in function void doSth(char *a), a local copy of a is modified in the scope of the function, but not out of it. If you wish to modify myString, a pointer to myString (&myString) should be given to the function. It is called passing by pointer :

char *myString;

doSth(&myString);

The prototype of the function is changed accordingly :

void doSth(char **a){
  ...
  *a = malloc(2*sizeof(char));
  strcpy(*a,b);
  ...
}

For the same reason, it is int a=1;printf("%d",a); (printf just needs the value of a), but int a;scanf("%d",&a); (scanf needs a pointer to a, to modify the value of a in the main).

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

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.