I was working on an assignment (details in another question). As part of it, I was increasing the size of the array. And found that when I try to initialize an array:
int arr[2097152]; // 8MB
I got segmentation fault … I think its because I am trying to declare an array that too large? Then I found the way to get around this is to use malloc. But being new to C (mainly use JavaScript/Python/Java …). I get very confused with pointers and stuff …
I’ve declared an array 8MB:
int *arr = malloc (MBs * 1024 * 1024 / sizeof(int)); // MBs = 8
But now … how do I access it, or write to it? When I use it like arr am I getting the address, and if I use *arr I get the 1st element?
Use it like
arr[index], just as if it were declared as an array. In C, the notationx[y]is exactly equivalent to*(x + y). This works in the case of an array because the array name is converted to a pointer to its first element.This is not a good approach (and doesn’t make it the size you want), because you don’t have the number of elements handy. You should declare it based on the number of elements, e.g.,
You need to multiply by the element size because malloc’s argument is a byte count.