编写C函数的正确方法是什么?返回char数组?

Edw*_*Lee 16 c string dynamic-allocation

我对Java非常熟悉,在C中则不是这样.

在Java中,如果我有一个方法可以做某事并返回一个String,它看起来像:

private String doSomething(...) {
    String s;
    // do something;
    return s;
}
Run Code Online (Sandbox Code Playgroud)

C中的句法等价物不起作用,是完全错误的:

char* doSomething(...) {
    char s[100];
    // do something;
    return s;
}
Run Code Online (Sandbox Code Playgroud)

当然我能做到:

char* doSomething(...) {
    char *s;
    s = malloc(100 * sizeof(char));
    // do something;
    return s;
}
Run Code Online (Sandbox Code Playgroud)

这会工作(我想!)但我很少看到代码这样做(是因为它不必要地填充堆?)

最常见的是,我看到:

bool doSomething(char *s) {
    // do something that copies chars to s
    return true;
}
Run Code Online (Sandbox Code Playgroud)

调用语句将是:

char s[100];
doSomething(s);
Run Code Online (Sandbox Code Playgroud)

如果在函数本身内部之前我不知道char数组的大小怎么办?即我无法在函数外声明char数组,然后将其传入.

处理这种情况的正确方法是什么?

Mit*_*eat 19

让调用代码负责分配内存.在示例2中传递缓冲区和缓冲区的长度:

bool doSomething(char *s, size_t buflen)
{ 
    // do something that copies chars to s up to max of buflen
    return true; 
} 
Run Code Online (Sandbox Code Playgroud)

这往往会减少泄漏,因为调用代码控制着内存管理.


ziu*_*ziu 5

静态分配案例(您必须考虑编译时的最大缓冲区大小)

buf[MAX_NO];
do(buf, MAX_NO);

_Bool do(char *s, size_t len) { 
// use len as boundary in your operations
}
Run Code Online (Sandbox Code Playgroud)

或动态分配案例(如你所说使用malloc并使用指针来保存缓冲区的位置和大小)

char *s = NULL;
size_t final_len;
do(&s, &final_len);

_Bool do(char** s, size_t* final_len) {
    size_t len = discoverSize();
    char* buf = (char*) malloc(sizeof(char) * len);

    *s = buf; //save memory location
    *final_len = len; //save buffer size
    // use len as boundary in your operations

}

// do whatever
free(s); //remember to free the buffer for politeness
Run Code Online (Sandbox Code Playgroud)