I'm currently writing an application where I need a C-function to return an array. I've read that C-functions directly can't return arrays but pointers to arrays, anyhow I still don't get it to work. I'm sending a string with several numerical values that I have to put into an array.
My code looks like this, where the main function is:
int main() {
char arr[3] = {0};
char *str = "yaw22test242test232";
foo(arr,3,str);
printf("%d\n",arr[0]);
return 0;
}
Where I want the foo function to return an array with the numbers 22, 242 and 232 on array positions 0, 1 and 2 respectively. The algorithm in the foo function works properly when used in the main program but not this way. Is there any way to work around this? What am I doing wrong? The foo function looks as follows:
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++;
}
}
}
arrvariable as acharinstead of adouble. Now it's working.