c - Assigning a char array to a char* -
i'm trying write function prefixes string length. can't seem assign char[] char *. mysteriously, if print out debugging code before assignment, works.
char *prefixmsgwlength(char *msg){ char *msgwlength; int msglength = strlen(msg); if (msglength == 0){ msgwlength = "2|"; } else{ int ndigits = floor(log10(abs(msglength))) + 1; int ndigits2 = floor(log10(abs(msglength + ndigits + 1))) + 1; if (ndigits2 > ndigits){ ndigits = ndigits2; } msglength += ndigits + 1; char prefix[msglength]; sprintf(prefix, "%d|", msglength); strcat(prefix, msg); // if uncomment below, msgwlength returned correctly // printf("msg: %s\n", prefix); msgwlength = prefix; } return msgwlength; }
the problem in code is
msgwlength = prefix;
here, you're assigning address of local variable (prefix
) pointer , try return
it.
once function finishes execution, local variables go out of scope , returned pointer invalid.
you need make prefix
pointer , allocate memory dynamically, if want retain it's existence after returning function.
Comments
Post a Comment