Differences with IDE/compilers array handling [duplicate] - c++

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C/C++: Array size at run time w/o dynamic allocation is allowed?
I'm in a class where we have a simple assignment to write a function that returns a pointer to a dynamic array and provide a stub to test it. I have this done so I'm not asking for help with the assignment. On the class blog another student suggests that it is intuitive that one should be able to do int Array[size]; where size is apparently a user defined variable.
I know that in standard C++, at least according to my text, an array must have a "constant integer expression...greater than zero" as a size declarator. Which implies to me that their example can't work. In fact, with VS2010 you get three errors when you try.
However, they explain:
I know that, you know that, even the g++ compiler in my Ubuntu install
AND the Bloodshed compiler on my WinXP install know that. For certain
levels of "know that" one would expect "int Array[size];" to work
(like it has in both the prior classes).
But evidently it fails to run on some people's VS compilers. One can
only assume that, since the common denominator is VS (and yes, I
confirmed this by asking a friend to check it on HIS box), that VS is
the problem. One of several.
There's already confusion because the I know that... part is referring to me telling them that there shouldn't be any reason to #include <new> in order to use new, but it seems they think we agree that there shouldn't be any reason to use new to allocate a dynamic array.(?)
So the question is obvious. Are there any compilers which will accept int Array[size];, where size is not a const int without error?

int Array[size];
where size is not a constant expression is a variable length array. They're a standard feature of C as of the 1999 ISO standard. The C++ standard has not adopted them, but some compilers support them as a language extension.
(Any C++ compiler, when invoked in conforming mode, must at least issue a diagnostic for an array type with a non-constant size.)
Incidentally, this isn't directly related to the IDE you're using; it's controlled by the compiler that your IDE invokes.
As for #include <new> there is a standard header by that name, but it's not necessary for the new operator, which is built into the language. The <new> header provides several overloaded versions of operator new and a few other declarations.

Related

Why is it allowed to declare an automatic array with size depending on user input? [duplicate]

This question already has answers here:
Why aren't variable-length arrays part of the C++ standard?
(10 answers)
Closed 4 years ago.
I'm using MinGW to compile for C++11 and I found out that this doesn't throw an error:
int S;
cin>>S;
char array[S];
While this does ("storage size of 'array' isn't known"):
char array[];
To me, the size is also unknown in the first case, as it depends on what the user input is.
As far as I knew, automatic arrays are allocated at compile time in stack memory. So why wouldn't the first example fail?
It's not. C++ doesn't have variable-length arrays, though some compilers allow it as an extension of the language.
You are apparently not aware of the GNU GCC extension Arrays of Variable Length. Therefore your first code compiles.
The error message is something different. You have to specify the array length.
gcc has the -pedantic switch - enabling this switch the compiler will report your first code as invalid:
warning: ISO C++ forbids variable length array ‘array’
Read also this thread What is the purpose of using -pedantic in GCC/G++ compiler?
Use very carefully compiler extensions because should you port your code to another compiler then you are in big trouble.
[This answers the original version of the question which asked about a static array; Deduplicator corrected this misconception, but now the question is missing a part.]
If your assumption that this piece of code defined a static array were correct, you'd be wondering for a good reason indeed: Something that is determined at compile time, like data with static storage duration, can obviously not depend on user input at run time. This truism is independent of any specific language.
The array defined in your code snippet has, by contrast, automatic storage duration, vulgo is created on the stack. A complete minimal working example would have made the case clearer: It would have shown that the code is in a function.
Objects with automatic storage duration can be created as needed at run time; there is no logical problem preventing that, which should fix your general headache ;-).
But note that, as some programmer dude correctly remarked, standard C++ nevertheless does not permit the definition of arrays whose size is not known at compile time; standard C does though, since C99. The rationale for C++ no following that amendment is that C++ provides better means for the use case, like the vector template. gcc, which is the compiler used in MinGW, permits this as an extension (and why not — it's available in the compiler anyway).

why does C++ forbid the declaration of a parameter with no type?

I would like to have the following method as a generic method for any array,
int arrayLength(`anyType` array[])
{
return sizeof(array) / sizeof(array[0]);
}
However it appears C++ doesn't allow any ambiguity of types at all,
why is this, and how should I go about getting around it?
Because types have to be pushed onto the stack and then popped back off, and the sizeof one type is not equal to the sizeof another type.
If the size of types being passed on the stack between functions is not fixed or known in advance, how can the compiler compile a function?
The solutions to this problem -- as others have noted -- is templates and macros, both of which dynamically generate code -- which is then, in turn, compiled -- at compile-time, appearing to "solve" the problem, but really only obviating or distracting you from it by offloading the work onto the compiler.
In Visual C++ there's a __countof() construct that does the same. It's implemented as a template for C++ compiling and as a macro for C. The C++ version errors out if used on a pointer (as opposed to a true array), the C version does not.
I think what you're really asking is "Why does C++ insist on static typing?"
The answer: because it's easier to write a compiler that generates small, fast programs if the language uses static typing. And that's the purpose of C++: creating small, fast programs whose complexity would be relatively unmanageable if written in C.
When I say "small", I'm including the size of any required runtime libraries.

Declaring local arrays using non-const variables to set the length, and it works? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
why a[n] is accepted in c during runtime?
Declaring the array size with a non-constant variable
I just wrote some code to test some other code and I needed an array as input data. As the size of the input data may differ, I declared the variable as follows:
float input[num_pixels_row][num_pixels_col][3];
where num_pixels_row and num_pixels_col are non-const variables which are set using input from the command line. I ran the code and it worked.
Then after a little while I noticed what I had just done and thought "Hey, wait a minute! This shouldn't work!!" But the strange thing is that it does. Since input is declared inside a function it should be allocated on the stack, but how can the compiler determine the stack frame if the size of the array isn't known?
I asked two colleagues and they were just as puzzled. By the way, I compiled the code using g++ 4.6.1
That's a gcc-specific compiler extension which makes your code sub-standard and nonportable. For example, this won't compile in Visual C++.
Variable length arrays are a part of the C99 specification, which gcc also allows in C++ programs.
I don't think this has been added to C++11 though, unfortunately. Though I'd suspect that since many C++ compilers also strive for C compliance that they'll end up supporting this as well.

can we give size of static array a variable

hello every one i want to ask that i have read that we can declare dynamic array only by using pointer and using malloc or newlike
int * array = new int[strlen(argv[2])];
but i have wrote
int array[strlen(argv[2])];
it gave me no error
i have read that static array can only be declared by giving constant array size but here i have given a variable size to static array
why is it so thanks
is it safe to use or is there chance that at any latter stages it will make problem i am using gcc linux
What you have is called a variable-length array (VLA), and it is not part of C++, although it is part of C99. Many compilers offer this feature as an extension.
Even the very new C++11 doesn't include VLAs, as the entire concept doesn't fit well into the advanced type system of C++11 (e.g. what is decltype(array)?), and C++ offers out-of-the box library solutions for runtime-sized arrays that are much more powerful (like std::vector).
In GCC, compiling with -std=c++98/c++03/c++0x and -pedantic will give you a warning.
C99 support variable length array, it defines at c99, section 6.7.5.2.
What you have written works in C99. It is a new addition named "variable length arrays". The use of these arrays is often discouraged because there is no interface through which the allocation can fail (malloc can return NULL, but if a VLA cannot be allocated, the program will segfault or worse, behave erratically).
int array[strlen(argv[2])];
It is certainly not valid C++ Standard code, as it is defining a variable length array (VLA) which is not allowed in any version of C++ ISO Standard. It is valid only in C99. And in a non-standard versions of C or C++ implementation. GCC provides VLA as an extension, in C++ as well.
So you're left with first option. But don't worry, you don't even need that, as you have even better option. Use std::vector<int>:
std::vector<int> array(strlen(argv[2]));
Use it.
Some compilers aren't fully C++ standard compliant. What you pointed out is possible in MinGW (iirc), but it's not possible in most other compilers (like Visual C++).
What actually happens behind the scenes is, the compiler changes your code to use dynamically allocated arrays.
I would advice against using this kind of non-standard conveniences.
It is not safe. The stack is limited in size, and allocating from it based on user-input like this has the potential to overflow the stack.
For C++, use std::vector<>.
Others have answered why it "works".

Creating array with constant

I was working on a program in Netbeans on Linux using a gcc compiler when, upon switching to Visual C++ on Windows 7, the code failed to compile as Visual C++ says it expected constant expression on several lines. On Netbeans, I simply did something similar to char name[fullName.size()];, while on Visual C++, I tried, among other things,
const int position = fullName.size();
char Name[position];
How can I create a constant to use for the array?
Note: I know about this question, but is there any way I can get this working without using vectors, since that would require a re-write of many parts of the program?
This is not possible in VC++. I know, pretty sad :(
The solutions include:
Create it on the heap
Make it constant
The new C++ standard (C++0x) proposes a 'constant expression' feature to deal with this. For more info, check this out.
In VC++ you can't do runtime declarations of stack array sizes, but you can do stack allocation via _alloca
so this:
const int position = fullName.size();
char Name[position];
becomes this:
const int position = fullName.size();
char * Name = (char*)_alloca(position * sizeof(char));
It's not quite the same thing, but it's as close as you are going to get in VC++.
C++ requires that the size of the array be known at compile time. If you don't mind using a non-standard extension, gcc does allow code like you're doing (note that while it's not standard C++, it is standard in C, as of C99).
I'd also guess that you could use a vector (in this particular place) with less trouble than you believe though -- quite a bit of code that's written for an array can work with a vector with only a re-compile, and little or no rewriting at all.
Your char name[fullName.size()]; is an example of a variable-length array which - as far as I know - are not standardized in C++ so you're at the mercy of the compiler.
[Slightly off-topic they're part of the C99 standard]