【发布时间】:2016-01-02 21:25:01
【问题描述】:
我正在编写一些处理字符串的函数,并发现我不能只将指针传递给函数并在其中进行 malloc,因为它不起作用。
例如:
char* string;
void create_string(char* output, char* text) {
len = strlen(text);
output = (char*)calloc(1, len);
strncpy(output, "test", len);
}
这有点令人费解,但无论如何它都行不通。我需要传递一个指向这样的指针的指针:
char* string;
void create_string(char** output, char* text) {
len = strlen(text);
*output = (char*)calloc(1, len);
strncpy(*output, "test", len);
}
并使用指针取消引用地址。好的,没关系。
接下来我想做一些类似于读取文件的函数。这个功能很好用。
char* ru_read_file(char* data, const char* file_path) {
FILE* fp;
size_t buffer = 4096;
size_t index = 0;
int ch;
fp = fopen(file_path, "r");
if (fp == NULL) {
printf("failed to open file: %s\n", file_path);
return "-1\0";
}
printf("filepath: %s\n",file_path);
data = (char*)malloc(sizeof(char) * buffer);
while (EOF != (ch = fgetc(fp))) {
data[index] = (char)ch;
++index;
if (index == buffer - 1) {
buffer = buffer * 2;
data = realloc(data, buffer);
if (data != NULL) {
printf(
"buffer not large enough, reallocating %zu bytes to "
"load %s\n",
buffer, file_path);
} else {
printf("failed to realloc %zu bytes to load %s\n", buffer,
file_path);
}
}
}
data = realloc(data, (sizeof(char) * (index + 1)));
data[index] = '\0';
fclose(fp);
return data;
}
上面的函数可以正常工作并且符合我的期望。接下来尝试将指向指针的指针作为函数的第一个参数传递,但我无法绕开它使其工作。
我虽然通过一个简单的指针来更新变量以通过指针取消引用它是可行的,但我遇到了段错误。
这里是代码
char* ru_read_file(char** data, const char* file_path) {
FILE* fp;
size_t buffer = 4096;
size_t index = 0;
int ch;
fp = fopen(file_path, "r");
if (fp == NULL) {
printf("failed to open file: %s\n", file_path);
return "-1\0";
}
printf("filepath: %s\n",file_path);
data = (char**)malloc(sizeof(char) * buffer);
while (EOF != (ch = fgetc(fp))) {
*data[index] = (char)ch;
++index;
if (index == buffer - 1) {
buffer = buffer * 2;
*data = realloc(data, buffer);
if (*data != NULL) {
printf(
"buffer not large enough, reallocating %zu bytes to "
"load %s\n",
buffer, file_path);
} else {
printf("failed to realloc %zu bytes to load %s\n", buffer,
file_path);
}
}
}
*data = realloc(*data, (sizeof(char) * (index + 1)));
*data[index] = '\0';
fclose(fp);
return *data;
}
如何将指针传递给指针并像工作示例一样使用它?我宁愿避免读取数据然后将其复制到另一个缓冲区。
【问题讨论】:
-
不要将
malloc& 朋友的结果投射到 C 中!在使用双指针之前,您应该使用其他机制。 函数有一个很好的特性:它们可以返回一个值。 -
请不要发布大量有效的代码。专注于没有的代码。
标签: c arrays pointers memory-management