malloc assigned to pointer

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 ?


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 char s, so "100" is a bit random. If you want 100 integers, do:

a = malloc(100 * sizeof *a);

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 int s.

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


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.

链接地址: http://www.djcxy.com/p/28464.html

上一篇: C语言:由malloc()返回的指针和转换

下一篇: malloc分配给指针