1

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

3 Answers3

5

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
3

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().

ani627
  • 5,578
  • 8
  • 39
  • 45
1

allocate memory to the pointer before using it

char *moving;
moving = malloc(100*sizeof(char));
scanf("%s", moving);
Haris
  • 12,120
  • 6
  • 43
  • 70
  • `sizeof(char)` is 1 by definition. And why `malloc`? Given the information in the question, `char moving[100];` works just as well. – Praetorian Sep 11 '14 at 04:36
  • i gave malloc because he seem to want to use pointers. and, sizeof(char) is 1 by defination, thats why i gave 100*sizeof(char) – Haris Sep 11 '14 at 04:38
  • Well, the OP is also confused by a very simple warning, so he seems to be a beginner, and what he *wants to use* is not necessarily what he *should be using*. And you wrote `100 * 1` knowingly because it's more expressive than writing `100`? – Praetorian Sep 11 '14 at 04:43
  • i wrote 100 * 1 so that he would know that using sizeof inside a malloc call is a better practice. – Haris Sep 11 '14 at 04:45