BillG BillG - 3 months ago 13
C Question

Store integers (32 bit) in array (which type? ) C programming

I got 32 bit integers that i want to store them in a dynamically allocated array and then send this array to others processes (in MPI )

int32_t data;


I am confused ,which type of data should i use so that i can have an array of size lets say , N with 32 bit integers?
How can this be implemented?

Answer

... which type of data should i use so that i can have an array of size lets say , N with 32 bit integers?

// The type of `p` is a pointer to a 32-bit signed integer.
int32 *p;

How can this be implemented?

// No need to use `int32_t` in the next line of code
//              size of 1 element ---v-------v * v--- element count
p = /* no cast needed here */ malloc(sizeof *p * N);
if (p == NULL) return Handle_Failure();

for (size_t i=0; i<N; i++) {
  // do something with p[i]
  p[i] = 42;
}

// free when done
free(p);
Comments