malloc problem. Giving test a few hours later. Problem in lecture

This is a discussion on malloc problem. Giving test a few hours later. Problem in lecture within the C Programming forums, part of the General Programming Boards category; Whats wrong with this code? Code: #include <stdio.h> #include<stdlib.h> int main() { int numslots,x; int *array; printf("Enter number of records:"); ...

  1. #1
    Registered User
    Join Date
    Oct 2012
    Posts
    14

    malloc problem. Giving test a few hours later. Problem in lecture

    Whats wrong with this code?
    Code:
    #include <stdio.h>
    #include<stdlib.h> 
    int main()
    {
      int numslots,x;
      int *array;
      printf("Enter number of records:");
      scanf("%i",&numslots);
      array=(int *)malloc(numslots*sizeof(int));
      if(array==NULL)
      exit(1);
      if(x=0;x<numslots;x++)
      {
      printf("%i\n",array[x]);
      }
    }

  2. #2
    qny
    qny is offline
    Registered User
    Join Date
    Sep 2012
    Posts
    355
    syntax error on line 12 ...

    if you meant that to be a for and are ussing a C89 compiler: no return from main.

    Also the cast to the return value of malloc is redundant. You don't check for errors in the scanf() call (what if the user enters "thirty" for the size?); and you print elements without a value: you need to assign to array elements before you print them.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 12-09-2012, 01:52 AM
  2. Replies: 10
    Last Post: 10-05-2012, 02:50 AM
  3. Need a urgent help, Test in hours time!!
    By wowolinda in forum C++ Programming
    Replies: 7
    Last Post: 02-02-2012, 08:17 PM
  4. Need a urgent help, Test in hours time!!
    By wowolinda in forum C Programming
    Replies: 2
    Last Post: 02-02-2012, 12:25 PM
  5. Help my program is giving a problem
    By zangetsu in forum C Programming
    Replies: 72
    Last Post: 04-04-2011, 11:56 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21