Stepii
Stepii

Reputation: 142

cast 2d char array to 2d int array

I have the following 2d array of unsigned chars to store an image as values from 0 to 255:

unsigned char img[MAX_DIM][MAX_DIM];

And I have a function that takes a 2d int array as parameter:

void transpose(int m[][MAX_DIM], int h, int w);

How can I pass the char array to that function? I tried something like this but it doesn't work:

transpose((int (*)[MAX_DIM])img, h, w);

Upvotes: 1

Views: 190

Answers (2)

Lundin
Lundin

Reputation: 213989

You could make a type-generic interface and implement two different transpose functions, one for 8 bit data and one for 32 bit data. Example:

#include <stdint.h>
#include <stdio.h>

void transpose_32 (size_t h, size_t w, uint32_t m[h][w]){ puts(__func__); }
void transpose_8  (size_t h, size_t w, uint8_t  m[h][w]){ puts(__func__); }

#define transpose(m,h,w) _Generic(**(m), uint8_t: transpose_8, uint32_t: transpose_32)(h,w,m)

int main(void)
{
  const size_t MAX_DIM = 10;
  uint8_t  img1[MAX_DIM][MAX_DIM];
  uint32_t img2[MAX_DIM][MAX_DIM];
  
  transpose(img1, MAX_DIM, MAX_DIM);
  transpose(img2, MAX_DIM, MAX_DIM);

  return 0;
}

Upvotes: 1

qiu
qiu

Reputation: 133

I would like to point out a few things that might help you.

First, if you want to pass an array as a function parameter, don't specify the size in brackets because there is no need to. In fact, think it is wrong.

Second, when you want to typecast something to int as I guess you are trying at your third line of code, the expression is : (int)charArray[] ; and not int charArray(*) [SIZE]

Third and most important, you cant typecast something that is non-arithmetic (char) to something that is (int). But what you can do is use the atoi function that converts an argument to int.

int atoi(const char *str);

Also, next time you want to pass an array to a function, you should prefer to reference it and pass the address of the array as a parameter and not the array with the content itself, because there is no way to return the whole array converted from the transpose function, even if you manage to process it the way you want.

I hope I helped even a little, but if your problem is not resolved, try posting the statement of your problem in order for us to be more able to help you.

Upvotes: 0

Related Questions