繁体   English   中英

调用者看不到函数返回的字符数组字符串

[英]Caller cannot see the char array string returned from a function

我从函数返回一个char指针。 但是,呼叫者无法看到该字符串。

char* getFileContent(char* file)
{

FILE* fp = fopen("console.txt", "r");

fseek(fp, 0L, SEEK_END);
size_t sz = ftell(fp);
fseek(fp, 0L, SEEK_SET);


char* message = (char*)malloc(sz+1);
char buf[sz+1];

size_t len = 0;
if (fp != NULL)
{
    len = fread(buf, sizeof(char), sz, fp);
}

printf("MALLOC SIZE:%d FILE SIZE:%d", sz, len);

strcpy(message,buf);    //Modified code. This line fixed the code
message[++len] = '\0';
//printf("MESSAGE:%s", message);

return(message);

}

这是来电者。 输出为空。

int main(int argc, char **argv, char **env)
{

char* msg = getFileContent(imagefile);

if(msg != NULL)
    printf("Output:%s \n", msg);

free(msg);

return 0;
}

请帮忙。

错误在这里:

printf("Output:", msg);

您不打印字符串。 尝试以下方法:

printf("Output: %s", msg);

需要%s来告诉printf()msg打印为字符串。


请注意,由于存在缓冲,您可能还需要添加\\n

printf("Output: %s \n", msg);

这是另一个小错误:

message[++len] = '\0';

应该:

message[len] = '\0';
strcpy(message,buf);    //Modified code. This line fixed the code
message[++len] = '\0';

我不确定是否可以保证在分配缓冲区buf之后它是否为空。 因此,读取后buf [len]可能不是'\\ 0',如果读取的文本中没有'0 \\',则您的strcpy可能会超出其范围。 因此,可以使用strncpy或将以上两行更改为

buf[len++] = '\0\;
strcpy(message,buf);

同样,第一个版本将'\\ 0'放在len + 1处,我认为这是错误的。 假设您已读取0个字节,然后len = 0,并且message [1]设置为'\\ 0',则message [0]未定义。

可能您的代码运行良好,因为发生了创建更改,分配的缓冲区buf要么用零填充,要么编译器主动将其无效。 但是据我所知,这不是C编译器必须执行的操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM