A dynamically allocated vector will behave in the same way as a common vector.
The reference of a vector is its first element in the case ptr[0]
, and ptr
points to the first element of the vector, and the remaining elements will be at a given distance from the first element, for example in this code the last element is at a distance of "4 ints" from the first element (ptr[4]
), therefore the use of the function sizeof()
, because we will use a "block" in the memory of the size we need in this case "5 ints" or 20 bytes (a variable of type int occupies 4 bytes). The same case applies to other types with the exception of a string, because a string is an array of the char type only in this case a string must always have the character as the last element\0
, soon an n character dynamic allocation will have to be sizeof(n+1)
.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *ptr = (int*)malloc(5 * sizeof(int));
for(int i = 0; i < 5; i++){
scanf("%d", &ptr[i]);
}
for(int i = 0; i < 5; i++){
printf("%d\n", ptr[i]);
}
free(ptr);
return 0;
}