7 c arrays pointers function character
甚至可能吗?假设我想返回一个包含两个字符的数组
char arr[2];
arr[0] = 'c';
arr[1] = 'a';
Run Code Online (Sandbox Code Playgroud)
从一个功能.我甚至用什么类型的功能?我唯一的选择是使用指针并使函数无效吗?到目前为止,我已经尝试过char*函数或char [].显然你只能有char(*[])的功能.我想避免使用指针的唯一原因是函数必须在遇到"返回内容"时结束.因为"something"的值是一个字符数组(不是字符串!),它可能会根据我通过main函数传递给函数的值来改变大小.感谢任何提前回复的人.
Jon*_*art 15
你有几个选择:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
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]);
}
}
Run Code Online (Sandbox Code Playgroud)
不要试图这样做
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! */
}
Run Code Online (Sandbox Code Playgroud)