Help with some syntax
Hello, I have not been programming for very long at all, I've been working my way through a book, reading stuff online and making some simple programs. I recently learned about malloc and I understand how to use it and why it is useful but some of the syntax has left me confused. Here is a line from a malloc() example program:
What does (int *) do here, what does it mean? I have seen it used in several examples of malloc.
ptr_one = (int *)malloc(sizeof(int));
In C++, this is a required syntax to tell the compiler that you want to convert the result from malloc, which is (void *) into (int *). In C, we normally write it like this
int *ptr_one = malloc(sizeof(int));
The compiler will automatically convert the right-hand side (void*) to the type of the left-hand side (int*). The type (int*) means pointer to int. The type (void*) basically means pointer to "something", where "something" is to be determined by the programmer.
EDIT: you will also see the above line written this way
This will allocate n items, each of the appropriate size (for example, int). This way if you later change the type, you need only change one word, example to allocate n doubles:
int *ptr = malloc(n * sizeof(*ptr));
double *ptr = malloc(n * sizeof(*ptr));
Thank you so much, I really appreciate it! :)