0

I want to pass the size of array, declared inside a function, to the same function. But then I got the warning "expressiong must a constant value". Are there solutions to this problem?

// Draws a sprite in the console using hex-coded sprite with a specific width
void hex_to_sprite(char* hex_number, int width, int size)
{
    // hex_number = array of hex-coded sprite 
    // width = width of sprite you want to draw
    // size = length of the hex_number multiplied by 4 (0 = 0000, 1 = 0001, etc.)
    char binary_coded_sprite[size] = "";

}

Should I learn dynamic allocation to fight this problem?

Venci
  • 25
  • 3

2 Answers2

1

You’re declaring binary_coded_sprite as a variable-length array, where the array size isn’t known until runtime. One of the restrictions1 on VLAs is that they may not be declared with an initializer, so

char binary_coded_sprite[size] = "";

needs to be

char binary_coded_sprite[size];

and you’ll either need to use strcpy:

strcpy( binary_coded_sprite, “” );

or just set the first element to 0

binary_coded_sprite[0] = 0;

to initialize it to an empty string.


  1. The other restrictions are that VLAs may not be declared static or at file scope, nor may they be members of struct or union types.

John Bode
  • 119,563
  • 19
  • 122
  • 198
0

From the code, it looks like the size variable is being computed from the length of the hex_number itself. So instead of passing the size variable in the function, just declare and compute the variable inside the function.