Vector pointer with dynamic allocation in C

Asked

Viewed 51 times

0

I managed to do this exercise inside main, however the same concept has not worked when using functions.

The aim of the program is simple, read six values and display them.

#include <stdio.h>
#include <stdlib.h>

int main(){
    int *i;
    int *valor[6];
    int temp = 0;

    i = (int *)malloc(sizeof(int));
    valor[6] = (int *)malloc(sizeof(int));

    for (*i=0; *i<6; *i = *i + 1){
        scanf("%d", (valor+*i));
    }

    for (*i=0; *i<6; *i = *i + 1){
        printf("%d\n", *(valor+*i));
    }
}

How is the code that tries to fulfill the same goal using functions:

#include <stdio.h>
#include <stdlib.h>

void write(int *i, int *valor){
    for (*i=0; *i<6; *i = *i+1){
        scanf("%d", &valor[*i]);
    }
}

void read(int *i, int *valor){
    for (*i=0; *i<6; *i = *i+1){
        printf("%d\n", valor[*i]);
    }

}

int main(){
    int *i = 0;
    int *valor;

    i = (int *)malloc(sizeof(int));
    valor = (int *)malloc(sizeof(int)*6);

    write(&i, &valor);
    read(&i, &valor);
}

1 answer

1


This will create an array with 6 integer pointers.

int *valor[6];

The positions of this array are numbered from 0 to 5. But here, you assign something to position 6, outside the array:

valor[6] = (int *)malloc(sizeof(int));

This is a violation of the size of the array. It should work by luck just because the invaded memory area other than the array should not be used for anything else.

Here, something strange happens:

scanf("%d", (valor+*i));

Use (valor+*i) is the same as &valor[*i]. Although equivalent, I strongly recommend the second way for being much more readable and understandable. Likewise, *(valor+*i) is equivalent to valor[*i].

The error is in these two lines:

write(&i, &valor);
read(&i, &valor);

What you wanted was this:

write(i, valor);
read(i, valor);

The reason is that the & is usually used to give the memory address of a variable, then creating a pointer. It occurs that i and valor are already pointers, and you want to pass the memory address to which they point. When using a & in each, you would be passing the memory address of the pointer, creating a pointer-to-pointer, which is not what you want.

Browser other questions tagged

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