Thread: Storing information in Arrays: Crash in Windows or Error in Linux

  1. #1
    Registered User
    Join Date
    Apr 2012
    Posts
    35

    Storing information in Arrays: Crash in Windows or Error in Linux

    I have an error happening here.
    1. I have attempted to write this function while I am learning C. It asks how many students and then asks for the age of each student.

    2. In Windows after 4 ages I get a crash that says its not working and it feezes. In linux I receive this error:

    studentAge.c: In function 'main':
    studentAge.c:30:5: error: format '%d' expects argument of type 'int *', but argument 2 has type 'int' [-Werror=format]

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char *argv[])
    {
      int numOfStudents=0,studentsAge[numOfStudents],a;  
          for(a=2;a>0;a--) {
          printf("How many students do you have (1-10)? ");
          if (scanf("%d*c",&numOfStudents)) {
            if(numOfStudents<0) {
            printf("Come on, how can you have a class with %d number of students?\n",numOfStudents);
            a=2;
            }
            else if(numOfStudents>10) {
            printf("Your class cannot hold more than 10 students.\n");
            a=2;
            }
            else
             a=0;
          }
          else {
            printf("A valid number was not entered.  This program will now exit.\n");
            numOfStudents=0;
            a=0;
          }
        }
      printf("What are your students ages?\n");
      for(a=0;a<numOfStudents;a++) {
        printf("%d: ",a+1);
        scanf("%d",studentsAge[a]);
      }
      system("PAUSE");	
      return 0;
    }

    Can someone please point me in the correct direction as to why this is happening?

    Thanks,

  2. #2
    Registered User ledow's Avatar
    Join Date
    Dec 2011
    Posts
    435
    I think you should read your error message and then change the line that it quite clearly indicates so that the only variable that's in use on that line is of the correct type.

    I think you could also read your very first line of main() and tell me how big studentsAge is and how many elements it can hold.

    Over and above that, I haven't tried to compile or debug your program so there may be lots of other problems (did you compile with -Wall to put on all warnings, for instance?)

    - Compiler warnings are like "Bridge Out Ahead" warnings. DON'T just ignore them.
    - A compiler error is something SO stupid that the compiler genuinely can't carry on with its job. A compiler warning is the compiler saying "Well, that's bloody stupid but if you WANT to ignore me..." and carrying on.
    - The best debugging tool in the world is a bunch of printf()'s for everything important around the bits you think might be wrong.

  3. #3
    Registered User
    Join Date
    Apr 2012
    Posts
    35
    I understand that numOfStudents could be a char over an int.
    If I knew what the error meant I would listen to it however I have never seen that error before. Line 30 is the scanf("....

    Just figured it out. The scanf doesn't have an & in front of the array.

    I am just learning so I would much appreciate if you wanted to compile and tell me what other mistakes I should not be making. This would help me become a better programmer. I just found out that system("PAUSE"); apparently doesn't work in Linux. It compiles just fine however when you run the program it errors out stating that it could not find that command so that must be a Windows thing.

  4. #4
    Registered User
    Join Date
    Apr 2012
    Posts
    35
    Here is the revised code. This was merely for a project that I was working on for some video tutorials. The tutorials are stupidly easy so I am attempting to make them a little harder by added my own twist to the required coding. If you want to compile it and look at it that would be great. I know that conio.h is a Windows thing. Other than that what seems to be the issue. This program merely figures out the average age for the students in a class of up to 10.

    Code:
    #include <stdio.h>
    #include <conio.h>
    #include <stdlib.h>
    
    int main(int argc, char *argv[])
    {
      char numOfStudents=0,studentsAge[numOfStudents],a=0,b=0;
      float sum=0;
          for(a=2;a>0;a--) {
          printf("How many students do you have (1-10)? ");
          if (scanf("%d*c",&numOfStudents)) {
            if(numOfStudents<0) {
            printf("Come on, how can you have a class with %d number of students?\n",numOfStudents);
            a=2;
            }
            else if(numOfStudents>10) {
            printf("Your class cannot hold more than 10 students.\n");
            a=2;
            }
            else
             a=0;
          }
          else {
            printf("A valid number was not entered.  This program will now exit.\n");
            numOfStudents=0;
            a=0;
          }
        }
      printf("What are your students ages? (5-65)\n");
      for(b=0;b<numOfStudents;b++) {
        printf("Student %d: ",b+1);
        if (scanf("%d*c",&studentsAge[b])) {
            if(studentsAge[b]<5) {
            printf("The youngest student allowed in this class is 5.\n",numOfStudents);
            b=b-1;
            }
            else if(studentsAge[b]>65) {
            printf("The oldest person allowed in this class is 65\n");
            b=b-1;
            }
            else {
            sum=sum+studentsAge[b];
            }
          }
          else {
            printf("A valid number was not entered.  This program will now exit.\n");
            sum=0;
            numOfStudents=0;
            b=0;
          }
      }
      if(sum>0) {
      printf("The total added age of every student is: %.00f\n",sum);
      printf("The average age of the students is %.02f.\n",sum/(float)numOfStudents);
      }
      system("PAUSE");	
      return 0;
    }

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You need to indent your code properly. You made some effort to do that, but it is still pretty inconsistent.

    You need to find out the numOfStudents before you create the array. At the moment, you are consistently creating studentsAge to be a variable length array of length 0, which is wrong.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Registered User ledow's Avatar
    Join Date
    Dec 2011
    Posts
    435
    Quote Originally Posted by scrfix View Post
    If I knew what the error meant I would listen to it however I have never seen that error before. Line 30 is the scanf("....
    This is quite a large chunk of learning to program - learning how the tools work and what the warnings / errors mean and how to fix them. Programming is 10% coding and 90% debugging, in my opinion. That gets less as you get better but learning to use your compiler and interpret its output is really a large part of learning C.

    If in doubt, warnings and errors are always "google-able" and should point you in the right direction.

    And, in keeping with my above opinion, YOU should be compiling with warnings ALWAYS on so that you can do that step yourself. Ignoring compiler warnings is like ignoring a "Bridge Out Ahead" sign. Actually getting the warning out of the compiler is the really easy bit (literally, if you can compile, it's maybe three or four extra characters on the line you use to compile or one tickbox on the IDE you use - but specific to the compiler setup that you use). Trying to find out what it means or why it applies to your code - that's more something that we can help with if you get really stuck, but is usually searchable.

    Quote Originally Posted by scrfix View Post
    I just found out that system("PAUSE"); apparently doesn't work in Linux. It compiles just fine however when you run the program it errors out stating that it could not find that command so that must be a Windows thing.
    The system command just runs the program you tell it to. You could literally put:

    Code:
    system("format C:\")
    and the system would run that command (DON'T DO IT!). In Windows (actually, from DOS history, but Windows keeps it around), the pause command is used to pause a batch file normally but is often abused by C tutorials to provide a "simple to understand" pause because they can't be bothered to explain the one/two lines of code it takes to implement a similar pause in cross-platform C (hint: Look at the keyboard input functions). In Linux, there are similar commands but would you really want to have to complicate matters by lots of:

    Code:
    #ifdef WIN32
      system("pause");
    #elif defined LINUX
      system(....)
    #else
      system(....)
    just to get the program to wait?

    And, in my experience, people only use that pause command because they don't know how to keep a DOS box open after the program has finished executing and they never leave it in finished programs, so it's literally ONLY a programmer's convenience (precisely because it's so un-portable). On Linux, that's not a problem because Linux doesn't try to hide the results of a command-line program and pretend the command line interface doesn't exist by default, like Windows does. system(ANYTHING) is likely to indicate someone who doesn't know how, or can't be bothered to, write a few lines of cross-platform code by sitting and thinking for five minutes. Same for if you see delay loops that just loop seven million times because it "feels" like the right length of time on someone's computer to pause.

    But all these things come by experience. If you take away any lesson today, let it be:

    1) ALWAYS compile with as many warnings as your compiler can possibly give.
    2) ALWAYS try to work out WHY it's warning you and what the problem COULD be (even if it doesn't affect you in your particular usage).
    3) The biggest part of programming is thinking why your program doesn't work (we've all been there, and all spend quite a lot of time there when we're learning, so it's a GOOD thing).

    - Compiler warnings are like "Bridge Out Ahead" warnings. DON'T just ignore them.
    - A compiler error is something SO stupid that the compiler genuinely can't carry on with its job. A compiler warning is the compiler saying "Well, that's bloody stupid but if you WANT to ignore me..." and carrying on.
    - The best debugging tool in the world is a bunch of printf()'s for everything important around the bits you think might be wrong.

  7. #7
    Registered User
    Join Date
    Apr 2012
    Posts
    35
    Thank you very much for that insight.
    I read the Bridge Out Ahead in your signature and laughed... lol
    I have taken both of your suggestions in to account and added more on to the program.

    Thank you for the System("PAUSE") functionality. I should have recognized that because I do write Batch. I didn't make the connection however.

    Laserlight, thank you for letting me know about the array initialization. I have fixed that.

    I have added a few more lines of code and commented everything. Thanks for all of your assistance.

    In linux, I have gedit set to treat all warnings as errors. In Dev-C++ I don't know how to set that up yet. I have used Visual Studio before but it has A LOT more than what I need at this point and I don't know everything that it does. I will probably switch over to that when I have a better understanding of errors and can understand debugging a little better.

    Here is the newest copy of the code. It compiles and works perfectly

    Code:
    /*********************************************/
    /* This program will ask how many students   */
    /* are in the class.  Based upon your answer */
    /* it will then ask what the ages are for    */
    /* each student.  From the answers provided  */
    /* it will round to the nearest whole number */
    /* the average age for the class.            */
    /*********************************************/
    #include <stdio.h> // Allows printf() function
    #include <math.h> // Allows the roundf function to be used.
    
    int main(int argc, char *argv[])
    {
    // introduce and initialize the variables to be used within the program.
      char numOfStudents=0,a=0,b=0;
      float sum=0,average=0;
    
    // Since we need to repeat the question if a wrong answer is provided we use a for loop.
    // The if statements determine whether or not a correct answer was provided.
          for(a=2;a>0;a--) {
          printf("How many students do you have (1-10)? ");
          if (scanf("%d*c",&numOfStudents)) {
            if(numOfStudents<1) {
              printf("Come on, how can you have a class with %d students?\n",numOfStudents);
              a=2;
            }
            else if(numOfStudents>10) {
              printf("Your class cannot hold more than 10 students.\n");
              a=2;
            }
            else
              a=0;
          }
          else {
            printf("A valid number was not entered.  This program will now exit.\n");
            numOfStudents=0;
            a=0;
          }
        }
    // Now that we know how many Students we have in the class, we need to initialize the array.
        char studentsAge[numOfStudents];
    
    // First, test to see if we made it out of the for loop above with a correct answer.
    // Then ask a proper question with the switch statement based upon the number of students
       if(numOfStudents>0) {
        switch(numOfStudents) {
          case 1: printf("What is your students age? (5-65)\n");
          break;
          default: printf("What are your students ages? (5-65)\n");
        }
       }
    
    // Great, we have made it asking about the age of the students.  Here we are going to use a
    // for loop to determine what the students ages are just like we did above.
    // We exit the program if a valid number is not entered.
      for(b=0;b<numOfStudents;b++) {
        printf("Student %d: ",b+1);
        if (scanf("%d*c",&studentsAge[b])) {
            if(studentsAge[b]<5) {
              printf("The youngest student allowed in this class is 5.\n",numOfStudents);
              b=b-1;
            }
            else if(studentsAge[b]>65) {
              printf("The oldest person allowed in this class is 65\n");
              b=b-1;
            }
            else {
              sum=sum+studentsAge[b]; // Used to add up all of the students ages
            }
          }
          else {
            printf("A valid number was not entered.  This program will now exit.\n");
            sum=0;
            numOfStudents=0;
            b=0;
          }
      }
    
    // Check to see if sum is greater than 0.  If it is then we must have a correct answer for both numOfStudents and sum.
    // We display the combined ages for everyone in the class.  We now figure out the average age for the class and display it.
      if(sum>0) {
        average=sum/(float)numOfStudents;
        printf("The total added age of every student is: %.00f\n",sum);
        printf("The average age of the students is %.0f.\n",roundf(average));
      }
      system("PAUSE"); // Proprietary to Windows. Keeps the command line window open when it reaches the end of the program.
      return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Obtaining useful information from Crash Report
    By @nthony in forum Windows Programming
    Replies: 6
    Last Post: 04-07-2009, 09:37 PM
  2. Error on Ubuntu/Linux but not Windows :O!
    By Akkernight in forum C++ Programming
    Replies: 9
    Last Post: 03-19-2009, 04:51 AM
  3. Storing Information then Displaying
    By peckitt99 in forum C++ Programming
    Replies: 11
    Last Post: 09-05-2006, 11:29 AM
  4. Storing information for lcd data
    By ekarapanos in forum C Programming
    Replies: 1
    Last Post: 04-02-2003, 02:04 PM
  5. Storing information in a file
    By Unregistered in forum C Programming
    Replies: 6
    Last Post: 11-18-2001, 09:05 AM