c - defining the CHAR pointer with variable size -
how can define char pointer correct or variable width?
my scenario below..
void processra(int _racount, char *rafile) { char *command; // how correctly define variable ? sprintf(command, "somecomm -r %s -n%d-%d ", rafile, (_racount - 1), (_racount - 1)); system(command); } in scenario, defining char pointer command. size of command depends on function passed variable rafile , following line's command.
char* in c come without associated storage. different languages fortran character type stands string of fixed size. either have define character array using char command[size+1], or use malloc() allocation (don't forget call free() when done string).
the tricky part correctly compute required length. however, in posix-2008 standard, there function called asprintf(), precisely need: combines function of sprintf() allocation of enough memory using malloc() (again, don't forget call free() when done string). usage follows:
void processra(int _racount, char *rafile) { char *command; // how correctly define variable ? asprintf(&command, "somecomm -r %s -n%d-%d ", rafile, (_racount - 1), (_racount - 1)); system(command); free(command); }
Comments
Post a Comment