Read and write multipas variaves with only one pointer

Asked

Viewed 25 times

-1

I was successful in doing task similar to the given code:

int *ptr[5], i;

for(i = 0; i < 5; i++){
    ptr[i] = (int *)malloc(1 * sizeof(int));
}

for(i = 0; i < 5; i++){
    scanf("%d", ptr[i]);
}

for(i = 0; i < 5; i++){
    printf("%d\n", ptr[i]);
}

However, I would like to do the same with something similar to this:

int *ptr = (int *)malloc(5 * sizeof(int));

You would also be welcome to provide the same information for a string of characters. Thanks in advance.

1 answer

0


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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.