简体   繁体   中英

I'm attempting to initialize an array in C using a variable and it won't work

I can't post my actual code because this is for a homework assignment and I don't want to risk cheating, I can give an example of my issue though. For example this is a version of what I'm trying to do, creating an array with a parameter.

void func(int length)
{
    int array[length] = {0};
}

This is oversimplified but it is stating that I can't do this and I receive this error:

Problem-01FAILED.c:48:16: error: variable-sized object may not be initialized int tempArray[t][2] = {}; ^ 1 error generated.

It also stated that I can't do the below, assign the value of the parameter to a variable and create an array within the function using that. It gives the same error.

void func(int length)
{
    int t = length;
    int array[t] = {0};
}

If anyone can tell me why this is happening and how to fix it, I would greatly appreciate it.

The size of the array is not known until runtime, ie it is a variable length array (VLA), and because of that it cannot be initialized.

If you want to set all values to 0, you can use memset :

memset(array, 0, sizeof(array));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM