字符串未初始化使用

时间:2018-11-15 09:03:48

标签: c string char malloc strcpy

我创建了这个非常简单的程序。我的目标是使输出显示String: hello world James,但我希望在我的test_function中分配问候世界。有人可以向我解释如何制作my_intro = "hello world"和命名my_name = "James"。这个问题围绕着我如何将malloc-ed char值解析回我的主函数。这不是int更改的重复。这是在解析char *

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void test_function(char *a_intro, char *a_name);

int main(void) {
    char *my_intro;
    char *my_name;
    test_function(my_intro, my_name);

    printf("String: %s %s\n", my_intro, my_name);
}

void test_function(char *a_intro, char *a_name) {

    char *intro = malloc(20);
    char *name = malloc(20);
    strcpy(intro, "hello world");
    strcpy(name, "James");

    a_intro = intro;
    a_name = name;

}

但是我得到的错误是:

testcode.c: In function 'main':
testcode.c:10:5: error: 'my_intro' is used uninitialized in this function [-Werr
or=uninitialized]
     test_function(my_intro, my_name);
     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
testcode.c:10:5: error: 'my_name' is used uninitialized in this function [-Werro
r=uninitialized]
cc1.exe: all warnings being treated as errors

另一种无效的解决方案:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void test_function(char *a_intro, char *a_name);

int main(void) {
    char *my_intro;
    char *my_name;
    test_function(&my_intro, &my_name);

    printf("String: %s %s\n", my_intro, my_name);
}

void test_function(char *a_intro, char *a_name) {

    char *intro = malloc(20);
    char *name = malloc(20);
    strcpy(intro, "hello world");
    strcpy(name, "James");

    *a_intro = intro;
    *a_name = name;

}

错误:

testcode.c: In function 'main':
testcode.c:10:19: error: passing argument 1 of 'test_function' from incompatible
 pointer type [-Werror=incompatible-pointer-types]
     test_function(&my_intro, &my_name);
                   ^
testcode.c:5:6: note: expected 'char *' but argument is of type 'char **'
 void test_function(char *a_intro, char *a_name);
      ^~~~~~~~~~~~~
testcode.c:10:30: error: passing argument 2 of 'test_function' from incompatible
 pointer type [-Werror=incompatible-pointer-types]
     test_function(&my_intro, &my_name);
                              ^
testcode.c:5:6: note: expected 'char *' but argument is of type 'char **'
 void test_function(char *a_intro, char *a_name);
      ^~~~~~~~~~~~~
testcode.c: In function 'test_function':
testcode.c:22:14: error: assignment makes integer from pointer without a cast [-
Werror=int-conversion]
     *a_intro = intro;
              ^
testcode.c:23:13: error: assignment makes integer from pointer without a cast [-
Werror=int-conversion]
     *a_name = name;
             ^
cc1.exe: all warnings being treated as errors

0 个答案:

没有答案