这可能吗? 假设我想返回一个包含两个字符的数组
char arr[2];
arr[0] = 'c';
arr[1] = 'a';
来自函数。我什至使用什么类型的功能?我唯一的选择是使用指针并使函数无效吗?到目前为止,我已经尝试过使用 char* 函数或 char[]。显然你只能有 char(*[]) 的函数。我想避免使用指针的唯一原因是函数在遇到“return something”时必须结束;因为“something”的值是一个字符数组(不是字符串!),它可能会根据我通过 main 函数传递给函数的值改变大小。感谢任何提前回复的人。
最佳答案
您有多种选择:
1) 使用 malloc()
在堆 上分配您的数组,并返回指向它的指针。您还需要自己记录长度:
void give_me_some_chars(char **arr, size_t *arr_len)
{
/* This function knows the array will be of length 2 */
char *result = malloc(2);
if (result) {
result[0] = 'c';
result[1] = 'a';
}
/* Set output parameters */
*arr = result;
*arr_len = 2;
}
void test(void)
{
char *ar;
size_t ar_len;
int i;
give_me_some_chars(&ar, &ar_len);
if (ar) {
printf("Array:\n");
for (i=0; i<ar_len; i++) {
printf(" [%d] = %c\n", i, ar[i]);
}
free(ar);
}
}
2) 在调用者的堆栈上为数组分配空间,并让被调用函数填充它:
#define ARRAY_LEN(x) (sizeof(x) / sizeof(x[0]))
/* Returns the number of items populated, or -1 if not enough space */
int give_me_some_chars(char *arr, int arr_len)
{
if (arr_len < 2)
return -1;
arr[0] = 'c';
arr[1] = 'a';
return 2;
}
void test(void)
{
char ar[2];
int num_items;
num_items = give_me_some_chars(ar, ARRAY_LEN(ar));
printf("Array:\n");
for (i=0; i<num_items; i++) {
printf(" [%d] = %c\n", i, ar[i]);
}
}
请勿尝试这样做
char* bad_bad_bad_bad(void)
{
char result[2]; /* This is allocated on the stack of this function
and is no longer valid after this function returns */
result[0] = 'c';
result[1] = 'a';
return result; /* BAD! */
}
void test(void)
{
char *arr = bad_bad_bad_bad();
/* arr is an invalid pointer! */
}
关于c - 如何从 C 中的函数返回字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31060404/