在将某些内容传递给函数后,我无法复制该内容。在主要功能中,我这样做了:
char *s;
function(s);
然后在函数中,我将某些内容复制到字符串中,但是当我在主体中打印该内容时,它会打印(null)
,为什么?
答案 0 :(得分:2)
像void function(char*s)
这样的函数需要一个指向正确分配的对象的指针(或NULL,以明确表示未传递任何有效的对象)。分配对象有几种方法,一种是malloc
,另一种是具有自动或静态存储持续时间的对象。
但是至少您不应该做一件事:传递未初始化的指针;该指针可能指向“某处”并产生未定义的行为,然后:
void function(char*s) {
if (s != NULL) { // valid?
strcpy(s,"Hello world!");
}
}
int main() {
char s1[20]; // automatic storage duration
char s2[] = "some initil value"; // automatic storage duration
static char s3[30]; // static storage duration
char *s4 = malloc(30); // dynamic storage duration
function(s1);
function(s2);
function(s3);
function(s4);
function(NULL); // explicitly something NOT pointing to a valid object
free(s4); // deallocate object with dynamic storage duration
// don't do that:
char* s5; // s5 is not initiaized
function(s5); // -> undefined behaviour
}