Skip to content

Commit 2f65421

Browse files
Jesse Williamsonronreiter
Jesse Williamson
authored andcommitted
Added explanation of the memory allocation function
1 parent abc6c58 commit 2f65421

File tree

1 file changed

+3
-1
lines changed

1 file changed

+3
-1
lines changed

Diff for: tutorials/learn-c.org/en/Dynamic allocation.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,9 @@ To allocate a new person in the `myperson` argument, we use the following syntax
1616

1717
person * myperson = (person *) malloc(sizeof(person));
1818

19-
This tells the compiler that we want to dynamically allocate just enough to hold a person struct in memory and then return a pointer of type `person` to the newly allocated data. The reason we write `(person *)` before the call to `malloc()` is that `malloc()` returns a "void pointer," which is a pointer that doesn't have a type. Writing `(person *)` in front of it is called *typecasting*, and changes the type of the pointer returned from `malloc()` to be `person`. However, it isn't strictly necessary to write it like this as C will implicitly convert the type of the returned pointer to that of the pointer it is assigned to (in this case, `myperson`) if you don't typecast it.
19+
This tells the compiler that we want to dynamically allocate just enough to hold a person struct in memory and then return a pointer of type `person` to the newly allocated data. The memory allocation function `malloc()` reserves the specified memory space. In this case, this is the size of `person` in bytes.
20+
21+
The reason we write `(person *)` before the call to `malloc()` is that `malloc()` returns a "void pointer," which is a pointer that doesn't have a type. Writing `(person *)` in front of it is called *typecasting*, and changes the type of the pointer returned from `malloc()` to be `person`. However, it isn't strictly necessary to write it like this as C will implicitly convert the type of the returned pointer to that of the pointer it is assigned to (in this case, `myperson`) if you don't typecast it.
2022

2123
Note that `sizeof` is not an actual function, because the compiler interprets it and translates it to the actual memory size of the person struct.
2224

0 commit comments

Comments
 (0)