1

How to cast this:

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

typedef struct dynamic_array_struct {
    void *data;
    size_t capacity;
    size_t size;
} vector;

int vector_init(vector *v, size_t cap){
    v->data = malloc(cap);
    if(!v->data) return -1;

    v->size=0;
    v->capacity=cap;

    return 0;
}

int main(){
    vector vec;
    vector_init(&vec, sizeof(int)*4);
    
    for(size_t i=0; i!=vec.size; i++)
        (int*)(vec.data)[i] = i;

}

I know void cannot be used in arithmetic, that's why I am trying to cast it to int, but I do not know the precedenece of 1)casting, 2)indexing. How to do it in the loop, whitout the need to take extra pointer (e.g int *p=(int*)vec.data) and then used it instead? How to make it all in once in the loop?

EDIT: So there are change:

int main(){
    vector vec;
    vector_init(&vec, sizeof(int)*4);

    for(size_t i=0;i<vec.capacity/sizeof(int);i++){
        vec.size++;
        ((int*)vec.data)[i] = i;
    }

    printf("%i\n",((int*)vec.data)[4]);
}

Could be vector be implemented this way?

milanHrabos
  • 2,010
  • 3
  • 11
  • 45

1 Answers1

2

Indexing has higher precedence than casting, so you have to use

((int*)vec.data)[i] = i;
Karim
  • 361
  • 1
  • 5