Pelles C forum

C language => Beginner questions => Topic started by: anujith on December 31, 2011, 08:15:26 AM

Title: Code stops working when scanf appears inside loops
Post by: anujith on December 31, 2011, 08:15:26 AM
The following code stops working when scanf is introduced inside the loop :-\

#include<stdio.h>

int main (void)

{
   int i;
   int m=0;

   for(i=0 ; i < 20; i++)
   {
      scanf("%d",m);
      printf("the value of m is %d \n", m);
      printf("hello \n");
   }
   return(0);
}
When scanf is removed from the same code, it works fine. Otherwise when the ouput window appears it says "code has stopped working" and closes immediately.  Could anyone tell me what is wrong with the above code ? Please correct me !!
Title: Re: Code stops working when scanf appears inside loops
Post by: CLR on December 31, 2011, 08:21:28 AM
Hi anujith. Welcome.  ;)

I got the following output.  Take a look..

warning #2234: Argument 2 to 'scanf' does not match the format string; expected 'int *' but found 'int'.
Title: Re: Code stops working when scanf appears inside loops
Post by: CommonTater on December 31, 2011, 08:22:10 AM
Scanf needs a pointer to the variable it's loading...
Code: [Select]
scanf(" %d", &m);

Put your typing cursor on the word scanf  in your source code and press F1 .... Works for any coloured keyword.
Title: Re: Code stops working when scanf appears inside loops
Post by: anujith on December 31, 2011, 08:32:15 AM
Thank You very much !! it worked  :) :)
Title: Re: Code stops working when scanf appears inside loops
Post by: anujith on December 31, 2011, 08:44:40 AM
Could anyone please correct me with the following code too..I think like u said in the above code may be I am missing something.

#include <stdio.h>

int main (void)
{char *name[20];
   char anu[20];
   int i;
   printf ("enter the strings\n");
   for( i=0; i<20 ;i++)
   {

   scanf("%s",name);
      printf("the string name declared as a pointer is %s\n", name);

   }
   scanf("%s",anu);
   
   printf("the string declared as a string of charaters are %s\n",anu);
   return (0);
}


Problem is the same ..code stops working and closes immediately. I couldnt figure out whats wrong..
Title: Re: Code stops working when scanf appears inside loops
Post by: CommonTater on December 31, 2011, 09:26:46 AM
Use char name[20]... not char* name[20] ... the former is a 20 character string, the latter is an array of pointers.
 
From the main menu click  -> project -> project options -> compiler -> Warnings = full
 
And pay attention to them... that's the compiler telling you what's wrong with your code.