Need help with old school C malloc

Started by
5 comments, last by Possibility 23 years, 1 month ago
I know C++ super well, but for my Mechanical Engineering class I need to write some code that can ONLY be compiled in pure C, no C++ So what is the equivalent of "new" and "delete" of C++ in C? Here is my code in C++ How do I do this in C?
  
struct POINT
{
    float x, y;
}

int main()
{
    int size;
    struct POINT *Point;

    size = 5;
    Point = new POINT[size];

    delete Point;

    return 0;
}
  
I tried: Point = malloc (struct POINT[size]); Point = malloc (sizeof (struct POINT[size])); Point = malloc (sizeof size*POINT); Point = malloc (sizeof size*(struct POINT)); And I tried several other ways, but nothing is working, some of them compile, but they give me a memory fault error when I run them. I would greatly appreciate any help. Possibility P.S. Yes I bitched at the TA for making it only straight C, but he is a dumb ass ME major who knows nothing about programming.
Advertisement
There''s nothing wrong with straight C . Here''s two equivelants (one new and one malloc) in C/C++:

int *abc = new int[50];
int *def = (int *) malloc(50*sizeof(int));

And, here''s how to delocate them:

delete [] abc;
free(def);

"Finger to spiritual emptiness underlying everything." -- How a C manual referred to a "pointer to void." --Things People Said
Resist Windows XP''s Invasive Production Activation Technology!
http://www.gdarchive.net/druidgames/
to make one:

struct POINT {
float x, y;
}
int main() {
struct POINT* p;
p = (struct POINT*)malloc(sizeof(struct POINT));
return 0;
}
then you use the p->x or p->y.
I agree with the anonymous poster, but if your making an array of objects, then you do a malloc like this:
p = (struct POINT*)malloc(sizeof(struct POINT)*elements);
Where elements is how many of the objects you want.

--Cloxs (Jared Klumpp)

Thanks guys, that worked pretty well. I also have one more question about pure C, how do your right to a file?

I need to output some variable to a text file. This kind of sucks only having a C++ book

Thanks again for any help.

Possibility
FILE *fp; //File pointer

fp=fopen("filename","w"); //Write to the file "filename"

int var; //Whatever you want to write

fwrite(&var,sizeof(var),1,fp); //Im pretty sure this is right...

fclose(fp);

=======================
Game project(s):
www.fiend.cjb.net
=======================Game project(s):www.fiend.cjb.net
You can also use putc() or putchar() (If I remember right, one is a macro for the other), and I think also fprintf() if you want formatted strings.

Harry.
Harry.

This topic is closed to new replies.

Advertisement