我目前正在编写一个应用程序,我需要一个 C 函数来返回一个数组。我读过 C 函数不能直接返回数组,而是返回指向数组的指针,无论如何我仍然无法让它工作。我正在发送一个包含多个数值的字符串,我必须将它们放入一个数组中。
我的代码是这样的,主要功能是:
int main() {
char arr[3] = {0};
char *str = "yaw22test242test232";
foo(arr,3,str);
printf("%d\n",arr[0]);
return 0;
}
我希望 foo
函数在数组位置 0、1 和 2 上分别返回一个数字为 22、242 和 232 的数组。 foo
函数中的算法在主程序中使用时可以正常工作,但不是这样。有什么办法可以解决这个问题吗?我究竟做错了什么? foo
函数如下所示:
void foo(char *buf, int count, char *str) {
char *p = str;
int k = 0;
while (*p) { // While there are more characters to process...
if (isdigit(*p)) { // Upon finding a digit, ...
double val = strtod(p, &p); // Read a number, ...
//printf("%f\n", val); // and print it.
buf[1-count-k] = val;
k++;
} else { // Otherwise, move on to the next character.
p++;
}
}
}
最佳答案
好吧,你在这里越界了:
buf[1-count-k] = val;
也许您的意思是 buf[k] = val;
和检查 if( k >= count )
以结束循环。
由于 char *buf
通常不能表示大于 127 的值,您应该使用足够大的整数类型,或者 double 类型,否则赋值 buf[*] = val;
从 double 类型到 char 类型,将导致未定义的行为。
关于c - 从 C 函数返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29917747/