Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can any pointer using malloc be considered an array?

Tags:

arrays

c

malloc

So, I am learning C right now, and wanted some clarification on some things.

I've learned that if we wanted to create a dynamic arrays we could use the following line of code:

int *arr = malloc(10 * sizeof(int));

I understand that, in this case, arr is a pointer being allocated the equivalent of an array of 10 ints in terms of bytes. I also understand that you can treat arr as an array (from arr[0] to arr[9].

Does that mean all pointers that are allocated memory can be treated as an array?

Like could this be treated as an array?

int *single = malloc(sizeof(int)); 

Or could this be treated as an array?

int *half = malloc(sizeof(int) * 1.5)
like image 936
Vineet Patel Avatar asked Oct 29 '25 13:10

Vineet Patel


1 Answers

  • Ignoring the array size, yes all pointers can be used arrays (meaning you can index them).
  • The number of elements should be an integer, with truncation for valid access (i.e., 1.5 means 1 item).
  • You request number of bytes from malloc, it makes sense that this is a multiple of the item size.
  • You should read about pointer arithmetic.
  • Array names can also be used as pointers (e.g., *array) but you can't assign to them or modify them (e.g., ++array).
like image 110
perreal Avatar answered Oct 31 '25 03:10

perreal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!