tags:

views:

79

answers:

2

what will be correct form of this code in c?

char *x = malloc(100);

code

#include <stdlib.h>
#include <stdio.h>
int main(){
    char *x=malloc(100);
    free(x);
    //in c++
    // char *x=new char[100];






     return 0;
}

here is errors

1>------ Build started: Project: memory_leaks, Configuration: Debug Win32 ------
1>Build started 8/1/2010 2:32:21 PM.
1>PrepareForBuild:
1>  Creating directory "c:\users\david\documents\visual studio 2010\Projects\memory_leaks\Debug\".
1>InitializeBuildStatus:
1>  Creating "Debug\memory_leaks.unsuccessfulbuild" because "AlwaysCreate" was specified.
1>ClCompile:
1>  memory_leaks.cpp
1>c:\users\david\documents\visual studio 2010\projects\memory_leaks\memory_leaks\memory_leaks.cpp(5): error C2440: 'initializing' : cannot convert from 'void *' to 'char *'
1>          Conversion from 'void*' to pointer to non-'void' requires an explicit cast
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:00.64
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
A: 

and you have to cast to "char *" like:

char * x = (char *)malloc(100*sizeof(char));

Because:

void *malloc(int);
Bigbohne
Not true. You don't have to cast in C (though you can).
el.pescado
+8  A: 

You have valid C code, but you're trying to compile with a C++ compiler. (In fact, if you renamed your source to memory_leaks.c, your development environment would probably automatically invoke a C compiler; with memory_leaks.cpp it invokes a C++ compiler.)

C and C++ are different languages. C++ looks like C with extra stuff, because it evolved from a language that was C with extra stuff. But it's now its own language. Don't mix them up.

In particular, if you add a cast before malloc, you might get C++ code that compiles, but you won't get good C++ code. Don't do it: if you're programming in C++, use new; if you're programming in C, use a C compiler.

Gilles