tproger tproger - 3 months ago 9
C Question

How return dynamic massive C

Why my way is doesnt work? "message" refers to Null

first function :

void messageToBit(FILE *m,char *message )
{
int fileSize = 0;
int k = 0;
char symb;
fseek(m, 0, SEEK_END);
fileSize = ftell(m);
fseek(m, 0, SEEK_SET);
message = (char*)malloc(8 * fileSize);
/* some action with message */

}


and call

void gg()
{
char* message = 0;

messageToBit(m, message);
....
}


why not pointing to the correct memory location?

Answer

The point is that you should pass a pointer to pointer as a parameter in order to get output value this way. It might be confusing for beginners so instead you can achieve the same result by returning a pointer:

char* messageToBit(FILE *m)
{
    int fileSize = 0;
    int k = 0;
    char* message;
    char symb;
    fseek(m, 0, SEEK_END);
    fileSize = ftell(m);
    fseek(m, 0, SEEK_SET);
    message = malloc(8 * fileSize); // as mentioned in comments, no cast
    /* some action with message */
    return message;
}

void gg()
{
 char* message = messageToBit(m);
....
}
Comments