【发布时间】:2020-03-18 16:35:16
【问题描述】:
在 C 语言中,我尝试在一个带有 malloc 的函数中创建一个字符串数组。
我没有返回数组,而是传递了它的地址和一个 size_t 变量地址。
我想保持数组动态,这意味着数组的大小由函数决定。
这个想法与以下链接相同,但这次使用字符串而不是整数:
https://stackoverflow.com/a/8437818/5036990
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int NB_ELEMENTS = 2;
const int MAX_STRING = 50;
void get_string_array(char **arr, size_t *arr_len) {
arr = malloc(sizeof(char *) * NB_ELEMENTS);
if (!arr) {
printf("the memory could not be allocated for the array\n");
return;
}
for (int i = 0; i < NB_ELEMENTS; i++) {
arr[i] = malloc(sizeof(char) * (MAX_STRING + 1));
if (!arr[i]) {
free(arr);
printf("the memory could not be allocated for element [%d]\n", i);
}
}
strcpy(arr[0], "hello");
strcpy(arr[1], "world");
printf("[inside the function] %s %s\n", arr[0], arr[1]);
*arr_len = NB_ELEMENTS;
}
int main(void)
{
char *x_array;
size_t x_length;
get_string_array(&x_array, &x_length);
for (int i=0; (size_t)i < x_length; i++) {
printf("%s\n", x_array[i]);
free(x_array[i]);
}
free(x_array);
return 0;
}
代码不起作用,我认为问题出在我声明指针并将其传递给函数的方式上。数组的构建方式应该没问题。
这是来自 gcc 的堆栈跟踪:
test-array-str.c:39:15: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
printf("%s\n", x_array[i]);
~^ ~~~~~~~~~~
%d
test-array-str.c:40:21: warning: passing argument 1 of ‘free’ makes pointer from integer without a cast [-Wint-conversion]
free(x_array[i]);
~~~~~~~^~~
In file included from test-array-str.c:2:
/usr/include/stdlib.h:563:25: note: expected ‘void *’ but argument is of type ‘char’
extern void free (void *__ptr) __THROW;
~~~~~~^~~~~
【问题讨论】:
-
函数的第一行丢弃了参数。也许你的意思是
*arr = malloc ...