C program(malloc) is not compiling in ubuntu 11.04

1.9k views Asked by At

I have installed the gcc compiler from this sudo apt-get install build-essential command

and my program code is

 #include<stdio.h>

 main()
   {
      int *b;

      b = (int*)malloc(10*sizeof(int));  

      printf("b=%u\n\n",b);
      printf("b+1=%u\n\n",(b+1));
      printf("b+2=%u\n\n",(b+2));

      b[2]=4;
      printf("*(b+2)=%d\n\n",*(b+2));

  }

when i try to compile this program from cc -c program.c command then i get some error

enter image description here

2

There are 2 answers

4
Mat On BEST ANSWER

You're missing #include <stdlib.h> (for malloc), and the format strings are wrong. Use %p to print pointers.

Also, you don't need to (and probably shouldn't) cast the return value of malloc (in C).

And the correct signature for main without parameters is:

int main(void)

Corrected code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *b;

    b = (int*)malloc(10*sizeof(int));

    printf("b=%p\n\n",  (void*) b);
    printf("b+1=%p\n\n",(void*) (b+1));
    printf("b+2=%p\n\n",(void*) (b+2));

    b[2]=4;
    printf("*(b+2)=%d\n\n",*(b+2));

    return 0;
}
0
Net4All On

I don't know why it worked in the video, it's probably using some strange non-standard compiler.

But your errors are because you are using int instead of unsigned int and you pass pointers to printf when it expects unsigned int.