Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Size Declaration Differences For C and C++

Tags:

c++

arrays

c

const int num = 16;
struct inputs{
       double X1[num];
       double X2[num];
};

Gives me an error:

error: variably modified ‘X1’ at file scope

The same was true for 'X2'.

But I remember the above is fine for C++, the above is fine (I may be mistaken for C++).

Can anybody clarify this for me?

like image 875
Rich Avatar asked Nov 03 '11 22:11

Rich


People also ask

Do you have to declare array size in C?

Arrays in C/C++ It is a group of variables of similar data types referred to by a single element. Its elements are stored in a contiguous memory location. The size of the array should be mentioned while declaring it.

Is array size fixed in C?

Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

What is size of array in C?

To determine the size of your array in bytes, you can use the sizeof operator: int a[17]; size_t n = sizeof(a); On my computer, ints are 4 bytes long, so n is 68. To determine the number of elements in the array, we can divide the total size of the array by the size of the array element.

Can you declare an array with a variable size in C?

size is a variable, and C does not allow you to declare (edit: C99 allows you to declare them, just not initialize them like you are doing) arrays with variable size like that. If you want to create an array whose size is a variable, use malloc or make the size a constant.


1 Answers

I can point you to a C FAQ: I don't understand why I can't use const values in initializers and array dimensions.

What it basically says is that num isn't a true constant, it's just read-only. To get a true constant you would need a #define num 16.

Also on that page: C is unlike C++ in this regard.

like image 67
cnicutar Avatar answered Sep 17 '22 14:09

cnicutar