在 C 中,如何用文本填充传递给函数的 char*?
我正在尝试创建一个将返回 int 的 C 函数,但在此过程中将填充作为变量传入的 char* 。我正在尝试的一个基本示例是:
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");
}
在 main.c 中:
char* myMethodOutput;
int myMethodInt = myMethod(2, myMethodOutput, 15);
printf("%d %s", myMethodInt, myMethodOutput);
运行时,整数显示在屏幕上,但文本不显示。
outMaxLen 变量旨在检查 char* 参数,以确保它足够大以容纳输出字符串。
除了strcat()之外,我还尝试过strcpy()和strncpy(),但都无济于事。 strcat() 不会向控制台显示任何文本,strcpy() 和 strncpy() 会使用消息 EXC_BAD_ACCESS 调用调试器。
我已经使用 strcpy_s 函数在 Windows API 中成功管理了此操作,但我现在正在 UNIX 机器上尝试。我可能错过了一些非常基本的东西!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要首先为指针分配一些内存,否则您只是写入内存中的某个随机区域。例如:
You need to assign some memory to the pointer first, otherwise you're just writing to some random area in memory. e.g.:
不要忘记 free,
myMethod()
也应该是void
类型don't forget to free, also
myMethod()
should be of typevoid
实际上,将参数命名为“缓冲区的长度”并不能创建足够长的缓冲区。
您无需为缓冲区分配任何内存;至少在示例代码中没有。
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.
在使用 myMethodOutput 之前,您应该使用 malloc() 或其他方法为其分配一些内存。写入未初始化指针的位置不是一个好主意。
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.