Strange Behavior?

Peter J. Holsberg pjh at mccc.edu
Wed May 8 12:07:20 AEST 1991


Here is an extract from a program a student wrote.  Note that he has
declared "input" incorrectly.  The strange behavior is that, when choice
"1" is made, the print function outputs all but the first line that was
entered.  Can anyone explain that in terms of what scanf() is doing to
memory near "input"?  (This is on a 386, if endianism matters.)

Thanks.
==============================================================
#include <stdio.h> 
#include <string.h>

void print(char *point[], int num);

#define MAX 9
#define SIZE 80
#define RETURN ""

main()
{
   int i;
   int num = 0, return_value = 1;
   char sentence [MAX][SIZE];   /* an array of strings */
   char *point[MAX];            /* an array of pointers to char */
   char *orginal[MAX];          /* an array holding the orginal sequence */
   char input;	/* SHOULD HAVE BEEN int input!!!  */

   printf("Input up to ten sentences \n");
   while(gets(sentence[num]) != NULL && num < MAX 
	     && strcmp(sentence[num], RETURN) != 0) 
   {
      point[num] = orginal[num] = sentence[num];  
      num++;
   }

	printf("Make a choice: ");
	scanf ("%d" , &input);      /* value converted to decimal integer
					but stored "in" a char ???  */
      
      switch(input)
      {
         case 1:  print(orginal,num);
                  break;
         case 5:  return;
         default: printf("Unknown response \n");
       }
}

void print(char *pointer[], int num)
{
    int count;

    for (count = 0 ; count < num ; count++)
       puts(pointer[count]);
}
======================================

Pete
-- 
Prof. Peter J. Holsberg      Mercer County Community College
Voice: 609-586-4800          Engineering Technology, Computers and Math
UUCP:...!princeton!mccc!pjh  1200 Old Trenton Road, Trenton, NJ 08690
Internet: pjh at mccc.edu	     Trenton Computer Festival -- 4/20-21/91



More information about the Comp.lang.c mailing list