-1

I have this problem with C.

I have the following statement.

int *a;
a=malloc(100);

And I get the following error:

error: invalid conversion from 'void*' to 'int*' [-fpermissive]

Any hints on this ?

Philip Kendall
  • 4,304
  • 1
  • 23
  • 42
s1k3s
  • 61
  • 2
  • 10
  • 7
    This is a legal conversion in C. Are you sure you're not compiling with a C++ compiler? – Bill Lynch Dec 12 '12 at 15:49
  • 1
    I'm pretty confident this is C++ - -fpermissive in particular is a gcc option for C++, not for C. – Philip Kendall Dec 12 '12 at 15:51
  • It is not clear what the question really is (looking to shut up compiler or fix programming error)? In any case this is too basic to be answered. – Lothar Dec 12 '12 at 16:12

3 Answers3

11

You are compiling your code as C++, in which the code you've used is not valid. For C though, it is valid and you should not add any cast.

Note, however, that the argument to malloc() is in chars, so "100" is a bit random. If you want 100 integers, do:

a = malloc(100 * sizeof *a);
Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606
0

When writing C compatible code in C++, where you have to use malloc because some pure-C library is going to free it, I would recommend writing up a quick typed malloc:

template<typename T>
T* typed_malloc( size_t count = 1 ) {
  return reinterpret_cast<T*>( malloc(sizeof(T)*count) );
}

which you then use like this:

int *a;
a=typed_malloc<int>(100);

which creates a buffer sized for 100 ints.

Adding in some additional stuff, like guarding against creating classes with non-trivial destructors in this manner (as you expect them to be freed without being destroyed), might also be recommended.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
-4

malloc is returning a void* pointer.

You should do :

a=(int*)malloc(100);

BTW: This statement is allocating 100Bytes and not 100 ints. LE: If you are compiling with gcc, this is not necessary. If you are compiling with g++, this is a must.

banuj
  • 3,080
  • 28
  • 34