pointer, malloc and char in C

Posted by user2534078 on Stack Overflow See other posts from Stack Overflow or by user2534078
Published on 2013-06-29T07:08:08Z Indexed on 2013/06/29 16:21 UTC
Read the original article Hit count: 165

Filed under:
|
|
|

im trying to copy a const char array to some place in the memory and point to it .

lets say im defining this var under the main prog :

char *p = NULL;

and sending it to a function with a string :

myFunc(&p, "Hello");

now i want that at the end of this function the pointer will point to the letter H but if i puts() it, it will print Hello .

here is what i tried to do :

void myFunc(char** ptr , const char strng[] ) {
    *ptr=(char *) malloc(sizeof(strng));    
    char * tmp=*ptr;
    int i=0;
    while (1) {
        *ptr[i]=strng[i];
        if (strng[i]=='\0') break;
        i++;
    }
    *ptr=tmp;
}

i know its a rubbish now, but i would like to understand how to do it right, my idea was to allocate the needed memory, copy a char and move forward with the pointer, etc..

also i tried to make the ptr argument byreferenec (like &ptr) but with no success due to a problem with the lvalue and rvalue .

the only thing is changeable for me is the function, and i would like not to use strings, but chars as this is and exercise .

thanks for any help in advance.

© Stack Overflow or respective owner

Related posts about c

    Related posts about pointers