0

I am trying to make a programm that turns a string into binary.

int len = strlen(word);
int array2[len] = ascii_v(word, len);

int ascii_v(string w, int l)
{
    int array1[l];
    for (int i = 0, i < l; i++)
    {
        array1[i] = word[i];
        return array1[l];
    }
    return array1[l];
}

"word" is a string that I get from the user.

The way I was planning on doing that is this: Get the word from the user, turn that word into and array of the ASCII values of each letter, turn each of the ACSII values into an array of the size 8 with with the binary code of the number: But when I tried to compile my code, I got this error: "error variable-sized object may not be initialized". I don't know what that means. Please let me know what I did wrong. I am very new to coding.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Ricci2003
  • 1
  • 1

2 Answers2

1

You have many problems with this code.

  1. You can't assign arrays (and the compiler will complain)

  2. You return the reference to the automatic storage array which will stop to exist when function returns.

  3. int array2[len] if array2 has static storage duration the length has to be a constant expression

0___________
  • 60,014
  • 4
  • 34
  • 74
0

This initialization of the array

int array2[len] = ascii_v(word, len);

is in any case incorrect and does not make sense.

An array may be initialized either using a string literal (if it is a character array) or a list of initializers enclosed in braces.

On the other hand, the function ascii_v returns an integer. Such an initialization is syntactically incorrect.

It seems you suppose that this return statement

return array1[l];

returns a whole array. Actually this return statement tries to return a non-existent element of the type int of the array with the index l while the valid range of indices is [0, l).

As for the error message produced by the compiler then you declared an array with the size that is not an integer constant expression. That is you declared a variable length array. Variable length arrays may not ne initialized in their declarations .

The expression len obtained like

int len = strlen(word);

is not a constant integer expression. It can not be evaluated at compile time.

From the C Standard (6.7.9 Initialization)

3 The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.

I think you mean something like the following

size_t len = strlen(word);
int array2[len];

//...

void ascii_v( string w, int array[] )
{
    while ( *w ) *array++ = *w++;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335