In C, how can a char* passed to a function be populated with text?
I am trying to create a C function which will return an int, but in the process will populate a char* passed in as a variable. A basic example of what I am trying is:
int myMethod(int input, char* output, int outMaxLen) {
int outValue = input开发者_开发技巧 * 5;
if (out < 10) strcat(output, "A small number");
else if (out < 20) strcat(output, "A medium number");
else strcat(output, "A large number");
}
In main.c:
char* myMethodOutput;
int myMethodInt = myMethod(2, myMethodOutput, 15);
printf("%d %s", myMethodInt, myMethodOutput);
When run, the integer displays on the screen, but the text does not.
The outMaxLen variable is intended to check the char* parameter to ensure it is large enough to accommodate the output string.
As well as strcat(), I have tried strcpy() and strncpy(), all to no avail. strcat() does not display any text to the console, and strcpy() and strncpy() invoke the debugger with the message EXC_BAD_ACCESS.
I have successfully managed this in the Windows API by using the strcpy_s function, but I am now trying on a UNIX box. I am probably missing something extremely fundamental!
You need to assign some memory to the pointer first, otherwise you're just writing to some random area in memory. e.g.:
char *myMethodOutput = malloc(256);
/* ... etc ... */
free(myMethodOutput);
char* myMethodOutput;
myMethodOutput = malloc(sizeof(char) * 200); //200 is example
don't forget to free, also myMethod()
should be of type void
Naming a parameter as "length of a buffer" does not, indeed, create a buffer long enough.
You don't allocate any memory for a buffer; not in the sample code at least.
You should allocate some memory for myMethodOutput with malloc() or something before you use it. It's not a good idea to write to the location of an uninitialized pointer.
精彩评论