florian2840
florian2840

Reputation: 49

initialize pointer in main and reserve memory in different function

in my main function I initialize a char pointer. This pointer I overgive a function setMemory(char *ptr) as a parameter where some memory shall be allocated. Additionally some data shall be stored in this function. Back in main function I try to read out the data to which the pointer shows, but not the correct data were outputted. Why?

int main(int argc, char *argv){
   char *ptr;
   setMemory(ptr);
   printf("String: %s", ptr); //Should print c
   return 0;
}

void setMemory(char *ptr){
   ptr = (char*)malloc(sizeof(char)*10);
   *(ptr) = 'c';
}

Upvotes: 0

Views: 116

Answers (3)

ameyCU
ameyCU

Reputation: 16607

Another way is to return the char * from you function to main -

char *setMemory(char *ptr){
    ptr = malloc(sizeof(char)*10);          // allocate memory
    memset(ptr,'\0',sizeof(char)*10);            // initialize ptr
    *(ptr) = 'c';
    return ptr;                             // return ptr 
 }

And in main call it like this -

char *ptr;
ptr=setMemory(ptr);

Note - Also correct type of argv as mentioned by in answer by Zenith. And also free the allocated memory.

Upvotes: 0

Emil Laine
Emil Laine

Reputation: 42828

Right now you're only passing a copy of the pointer, and modifying the local copy in setMemory.

If you want to modify the original pointer passed to setMemory, you need to pass a pointer to it:

void setMemory(char **ptr) {
   *ptr = malloc(sizeof(char) * 10);
   (*ptr)[0] = 'c';
   (*ptr)[1] = '\0';
}

Note the null character, which is needed to terminate each C-style string.

and call it with

setMemory(&ptr);

Also, don't cast the result of malloc, it's redundant.

Also your main() signature is wrong, char *argv should be char **argv (or preferably const char **argv, since modifying **argv is undefined behavior anyway).

Upvotes: 0

Mr. E
Mr. E

Reputation: 2120

Based on ameyCU answer

char* setMemory(int size){
    char *ptr = calloc(size, sizeof(char)); //Used calloc instead of malloc + memeset to \0
    *ptr = 'c';
    return ptr;
}

And called

char *ptr = setMemory(10);

Upvotes: 1

Related Questions