Search code examples
carraysvisual-studioc89

How do I set values inside a global, fixed-size array, in C (in Visual Studio)?


A part of my VS2012 Windows Phone project is in C. I've been struggling during one day trying to initialize an array to put stuff inside it.

Whenever I try to initialize it as global (outside any function), then I get a message telling me that I can't initialize it with a value that isn't a const.

const char* myArray = (const char*)malloc(256);
// Bad code: this isn't initialized with a const

If I don't initialize it with a value, then I'll have a message telling me to give it a value. So I assign a NULL value to the array.

const char* myArray = NULL;

Then I need to set a size somewhere, so I set the size within my main, or first function:

int myFirstFunctionInTheCode()
{
    myArray = (char*)malloc(256);    
}

Then I get something like: ';' expected before type

So I'm searching on forum and read that C in Visual Studio is C89, thus, I need to declare then to assign on two separate line, which isn't true elsewhere in my code, so I'm completely mixed-up about -real- standards. But I still get the same error when doing it on two lines.

I then decide to use some other tools from the available VS libraries to find out that in C, I can't include sstream, streambuf, etc, otherwise my whole project fails with thousands of bugs. So I could use boost to get a real stream libraries, but it's not compatible with Windows Phone because of some thread usage.

How do I set values inside a global, fixed-size array, in C (in Visual Studio)?

What I want to achieve is similar to something in C# like it:

static byte[] gentleCSharpArray = new byte[256];

private void easyShotCSharpFunction()
{
    gentleCSharpArray[0] = 0x57;
    gentleCSharpArray[1] = 0x54;
    gentleCSharpArray[2] = 0x46;
}

I never spent so much time trying to assign a value to an array, so I guess I'm totally wrong with my global char* arrays?


Solution

  • You either:

    const char my_array[] = "abcdef";
    

    or:

    char *my_array;
    
    int main(void)
    {
        my_array = malloc(some_size);
        /* initialize elements of my_array */
    }
    

    Example 1 makes no sense because you are attempting to initialize a static variable at runtime. Example 2 makes no sense because you are attempting to modify a const object. Essentially, you did the opposite of what could work in either situation.


    What I want to achieve is similar to something in C# like it:

    static byte[] gentleCSharpArray = new byte[256];
    
    private void easyShotCSharpFunction()
    {
        gentleCSharpArray[0] = 0x57;
        gentleCSharpArray[1] = 0x54;
        gentleCSharpArray[2] = 0x46;
    }
    

    Ok, then you want;

    unsigned char arr[256];
    
    void c_version(void)
    {
        arr[0] = 0x57;
        arr[1] = 0x54;
        arr[2] = 0x46;
    }