user32882
user32882

Reputation: 5877

programming in C: "expected constant expression" error in Visual Studio

I am following this video tutorial on sorting arrays using C code. Unlike the video, which uses codeBlocks, I am using Visual Studio to compile/run my code. When attempting to run the following

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>


int main()
{
    
    int i,temp,swapped;
    int howMany = 10;
    int goals[howMany];

    
    return 0;

    }

I get the following error:

Error 1 error C2057: expected constant expression d:\temp\c tutorials\c tutorials\main.c 17 1 C Tutorials

Error 2 error C2466: cannot allocate an array of constant size 0 d:\temp\c tutorials\c tutorials\main.c 17 1 C Tutorials

I am using exactly the same code as on the video. Why will visual studio not allocate 10 bits of memory using the previously declared howMany variable?

Upvotes: 1

Views: 4297

Answers (2)

Harrison
Harrison

Reputation: 333

You can simply define like this,

int goals[10];

Or you can modify howMany to const like this,

const int howMany = 10;

Or you can define howMany as a macro outside like this,

#define howMany 10

Upvotes: 0

Motun
Motun

Reputation: 2149

You could allocate dynamically, use malloc or calloc. Note that by this way, you are allocating from the heap.

#include <stdlib.h>

const int howMany = 10;
int* goals = malloc(howMany * sizeof(int));

You should check the pointer in case malloc failed:

if (goals == NULL){
    /* Something went wrong, act accordingly */
} else{
    /* Move on in here, or just don't write the else part at all */
}

Then you can access this array by indexing:

goals[0] = 2017;

If you need to resize this array, you can use realloc. However while doing this, first use a new pointer and then check it again. Suppose you needed a bigger array in run-time. In this case, I will assume howMany wasn't declared as const int so it can be reassigned without some pointer hack.

howMany = 50;
int* temp_new_goals = realloc(goals, howMany * sizeof(int));
if (temp_new_goals == NULL){
    /* Something went wrong again */
} else{
    /* No problems, assign the new pointer. Don't worry, your old data remains still. */
    goals = temp_new_goals;
}

At the end, don't forget to free the memory you allocated. You don't want memory leaks:

free(goals);

Upvotes: 4

Related Questions