scanf is using an uninitialized variable; C [duplicate]

霸气de小男生 提交于 2021-02-17 03:29:51

问题


I'm sure there just a silly mistake here, however, I can't figure it out. This is part of my code:

char *moving;
scanf("%s", moving);

When I compile it with gcc, it says the following:

newmatrix.c:38:7: warning: ‘moving’ is used uninitialized in this function [-Wuninitialized]

Line 38 is the scanf

How do I fix this? Thanks


回答1:


Allocate memory for moving before using it. Use malloc().

moving is pointer of char type. Before storing the string in moving, you need to allocate memory for it.

char *moving;
moving = malloc(100); 
scanf("%s", moving);

OR

Simply change char *moving to char moving[256].

Also instead of scanf() use fgets().




回答2:


You can allocate memory before you call scanf(). For example:

char moving[256];
if (scanf("%255s", moving) != 1)
    …oops — presumably EOF…

You could use malloc() instead of a simple array, but then you have to remember to free the allocated memory. OTOH, if you want to return the data from the function where it is read, it may well be more convenient to use malloc(), but consider passing a pointer to the space (and its size?) to the function.

Or you can have scanf() do the memory allocation for you (check the manual page for scanf() carefully — read it weekly until you've memorized (enough of) it):

char *moving;
if (scanf("%255ms", &moving) != 1)
    …oops — probably EOF, but perhaps OOM (out of memory)…
…use moving…
free(moving);

Yes, this is one of the lesser-known options in POSIX-standard scanf(); it is not a part of Standard C.




回答3:


allocate memory to the pointer before using it

char *moving;
moving = malloc(100*sizeof(char));
scanf("%s", moving);


来源:https://stackoverflow.com/questions/25779112/scanf-is-using-an-uninitialized-variable-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!