More quetions:
i get an unrecognized 'eld' from mai structure.
header contains:
const int c=10;
struct Array
{
int n;
int els[c];
};
The error i get is:
error: request for member 'els' in 'A', which is of non-class type 'Array [(((unsigned int)(((int)a) + -0x000000001)) + 1)] {aka Array [(((unsigned int)(((int)a) + -0x000000001)) + 1)]}'
Code:
Array arrayInp()
/* Create 2 vectors by the length defined by the user*/
{
int a,b,i;
cout<<"enter length of the first array: ";
cin>>a;
cout<<"enter length of the second array: ";
cin>>b;
Array A[a],B[b];
cout<<"insert first array:";
for (int i=0;i<a;i++)
{
cin>>A.els[i];
}
cout<<"insert second array:";
for (int i=0;i<a;i++)
{
cin>>B.els[i];
}
return A,B;
}
One more error, my return isent right can someone explain me a way how to return the array structures from the functions?
after build errors:
..\scr\main.cpp:32:10: warning: left operand of comma operator has no effect [-Wunused-value]
..\scr\main.cpp:32:10: error: could not convert '(0, ((Array*)(& B)))' from 'Array*' to 'Array'
..\scr\main.cpp:11:10: warning: unused variable 'i' [-Wunused-variable]
..\scr\main.cpp:33:1: warning: control reaches end of non-void function [-Wreturn-type]
This:
Array A[a]
defines an array of Array called A. You need to index A to access the members of Array or (I suspect this was your intention) change declarations to:
Array A, B;
Just to point out that variable length arrays are not standard C++ (I think they are a GCC extension).
The return statement:
return A,B;
is using the comma operator. In this case B will returned and is the cause of warning: left operand of comma operator has no effect.
The unused variable i warning is complaining that the i declared at the beginning of the function int a, b. i; is unused, this is due to redeclaration of i in both for loops: either remove the i from top declaration or don't redeclare in for loops.
Without seeing the full source code, I suspect the warning: control reaches end of non-void function is because there is no return 0; in int main().
You probably want A[i].els, not A.els[i].
I addition to hmjd comment, I think I should point out that this has already been implemented but better by the standard library; it is almost always better to use std library constructs where possible because they are well know to other C++ developers, their functionality is well documented and finally they have a uniform interface which integrates with other standard features (such as standard algorithms).
There are two construct you can use
The fixed size:
std::array<int, 6> array_; //an array of six elements
And the resizable
std::vector<int> vector_(6); //a container of six elements.
http://en.cppreference.com/w/cpp/container/array
http://en.cppreference.com/w/cpp/container/vector
Related
Hello first thing first forgives me if I have mistakes in my English, I am beginner in c++ and I need help with this problem please
//global variables
int RangeOfArray;
int arr[RangeOfArray-1]; // error: array bound is not an integer constant before ']' token
void functionOne(){} // I need to access the array here.
void functionTwo(){} // as well here.
int main (){
cout<<"Type the length number of the array : ";
cin >> RangeOfArray;`
}
As you can see I need the array (arr) everywhere in my program but I can't why? I don't know
An array needs a size that can be known at compile time. RangeOfArray is not known at compile time. Also, you are declaring the array and then trying to assign a size to it, which is not possible. You'll need dynamic arrays for this purpose:
#include <iostream>
int RangeOfArray;
int* arr;
int main() {
std::cout << "Type the length number of the array : ";
std::cin >> RangeOfArray;
arr = new int[RangeOfArray];
}
..or preferably, std::vector:
#include <iostream>
#include <vector>
int main() {
std::cout << "Type the length number of the array : ";
int vec_size; std::cin >> vec_size;
std::vector<int> vec;
vec.resize(vec_size);
}
Any of the 2 options work.
In these declarations
//global variables
int RangeOfArray;
int arr[RangeOfArray-1]; // error: array bound is not an integer constant before ']' token
there is declared the global variable RangeOfArray that is implicitly initialized by zero and then there is declared the variable length array arr with the size -1 that is implicitly converted to the maximum value of the type size_t due to the usual arithmetic conversions because in C++ an expression that specifies a size of an array in its declaration is converted to the type size_t.
For starters variable length arrays is not a standard C++ feature. And moreover you may not declare a variable length array with static storage duration.
And secondly using the expression -1 as the size of an array does not make a sense.
If you need a global variable that simulates an array then use the standard container std::vector<int>.
For example
#include <iostream>
#include <vector>
//global variables
std::vector<int> arr;
void functionOne(){ /* ... */ } // I need to access the array here.
void functionTwo(){ /* ... */ } // as well here.
int main()
{
size_t RangeOfArray;
std::cout<<"Type the length number of the array : ";
std::cin >> RangeOfArray;`
arr.resize( RangeOfArray );
//...
}
The vector provides member function size that reports the current number of elements stored in the vector. So you need not to make the variable RangeOfArray global.
Pay attention to that it is not a good idea to use global variables.
So you could declare the vector in main and pass it by reference to functions where it is required.
why [I cannot use the array]?
The error message that you quoted explains why:
error: array bound is not an integer constant before ']' token
The size of an array must be compile time constant. RangeOfArray-1 is not compile time constant. Hence it cannot be used as the size of an array.
If you want to create an array whose size is determined at runtime, you must use dynamic storage. Simplest solution is to use std::vector from the standard library.
Another issue is that you try to use the variable before it has been assigned a value (although it has been zero-initialised). That approach doesn't work in imperative programming languages such as C++. You must assign a value before you can access it.
Mistake 1
In standard C++, the size of an array must be a compile time constant. So when you wrote:
int RangeOfArray;
int arr[RangeOfArray-1]; //not standard c++
The statement int arr[RangeOfArray-1]; is not standard C++ since RangeOfArray - 1 is not a constant expression.
Mistake 2
From Array declarators documentation:
If the expression is a constant expression, it shall have a value greater than zero.
This means even if RangeOfArray was a constant expression, due to static initialization, RangeOfArray will be initialized with 0 and so the expression RangeOfArray - 1 evaluates to the negative integer -1. And according to the above quoted statement, int[-1]; isn't valid.
Solution
Better would be to use std::vector as shown below:
#include <iostream>
#include<vector>
//global variables
std::vector<int> arr; // empty vector
void functionOne(){
std::cout<<"functionOne called with: "<<arr.size()<<std::endl;
}
void functionTwo(){
std::cout<<"functionTwo called with: "<<arr.size()<<std::endl;
}
int main (){
int RangeOfArray = 0;
std::cout<<"Type the length number of the array : ";
std::cin >> RangeOfArray;
//resize the vector named arr
arr.resize(RangeOfArray);
//call functionOne
functionOne();
//call functionTwo
functionTwo();
}
I am a newbie programmer in c++ started my Computer Science degree. I got a problem with my assignment.
You need to make a function char calculate_daily_sale(int []).
You need to define and read an array of integer values of length 10 in the main() function.
Write a function charcalculate_daily_sale (int []) that accepts the array as argument from the main() function. The function will sum the values of array. If the values are greater than or equal to 15,000 the
function return ‘y’ back to the main function, otherwise ‘n’ is returned from the function.
This is the code that I managed to write:
#include <iostream>
using namespace std;
char calculate_daily_sale(int[])
{
int arr[10];
int *ptr[10];
int sum=0;
for(int j=0; j<=9; j++)
{
ptr[j]=&arr[j];
sum=sum+arr[j];
cout<<sum;
}
}
int main()
{
int n,y;
int arr[10];
int *ptr[10];
for(int i=0; i<=9; i++)
{
ptr[i]=&arr[i];
cin>>*ptr[i];
}
if(calculate_daily_sale(int[])>=15000)
{
return y;
}
else
{
return n;
}
return 0;
}
The error that I am getting is:
expected primary expression before 'int'
You need to take a step back and learn the basics of C++ programming.
Some points you should be looking at are:
char calculate_daily_sale(int[])
The function has a return type of 'char' and therefore needs a return statement.
The function parameter is not named and not used. It can be removed entirely.
if(calculate_daily_sale(int[])>=15000)
When calling a function, you need to pass a value, not a type 'int[]'
The return type of is char so it seems odd to be comparing it with 15000.
return y and return n
n and y are uninitialized.
A value returned from main is simply an error code returned to the operating system that runs the programme. It seems unlikely that you want to return these numbers, whatever they are. My reading of the spec is that you need to be returning the characters 'n' and 'y' (for 'yes' and 'no') from your calculate_daily_sale and to main, which is why the return type is char.
Error messages always mention line number. This is the way you can locate the error precisely. Assuming your error is in this line
if(calculate_daily_sale(int[])>=15000)
You probably meant to pass the array arr to calculate_daily_sale:
if(calculate_daily_sale(arr)>=15000)
Followup to Range-for-statement cannot build range expression with array function parameter.
The original error is:
error: cannot build range expression with array function parameter 'arr' since parameter with array type 'int []' is treated as pointer type 'int *'
The failing code:
void print(int (&arr)[int]){
for(int x: arr)
cout<<" "<<x;
cout<<endl;
}
The fixed code:
template<int N>
void print(int (&arr)[N]){
for(int x: arr)
cout<<" "<<x;
cout<<endl;
}
My question is, why do we have to fix it like this? I do not understand what int (&arr)[int] means.
Your question is a little confusing because your first example is not valid code.
However, I think there is still an explanation to provide here. Here's a "correct" version of your first function:
void print(int (&arr)[5]){
for(int x: arr)
cout<<" "<<x;
cout<<endl;
}
void foo() {
int x[5];
int y[3];
print(x);
print(y); // Bam! error!
}
The print() function takes an array of 5 ints as a parameter. Note that this can only be done with statically sized arrays. The compiler must know the size of the array when compiling the function, and that function will only work for that particular array size.
Let's contrast that with your second, valid example.
A single array size, that's kind of annoying. What if I don't want to write a different function for various array sizes? We could always pass a pointer and a size, but that's kind of ugly (not to mention error prone).
Instead, we can give the compiler a function template. That is, not a function, but a recipe on how to create functions on-demand.
template<int N>
void print(int (&arr)[N]){
for(int x: arr)
cout<<" "<<x;
cout<<endl;
}
The constant 5 has been replaced by the placeholder constant N (which will have to be an int, as specified in the template declaration. This way, the compiler will generate a separate print() function for each array size we call it with.
The rationale behind that is that C++ only allows constepr for array dimensions. The template version ensures that N is a constepr (a compile time constant) while the incorrect one let think that you intend to use a run time integer value for the array size - which is unfortunately forbidden in C++
I'm writing an array-based code that is throwing me some confusing errors after failing to compile. I have searched the internet for sample code that I understand more or less but it is helpful for me to identify errors in my own code / thought process.
The task at hand is to create a function that accepts an array of an unknown amount of integers and sums the even numbers in the array. I am told the last entry of the array is -1, but I don't think this information is useful.
Here is my code:
#include <iostream>
using namespace std;
int sumEven(int myArray[])
{
int len = (sizeof(myArray) / sizeof(myArray[0]));
int i = 0;
int count = 0;
while (i < len)
{
if (myArray[i] % 2 == 0)
{
count = count + myArray[i];
}
i++;
}
return count;
}
I attempt to define len as the number of array elements. I think this didn't work since one error refers to this line:
prog.cpp:13:18: error: sizeof on array function parameter will return size of 'int *' instead of 'int []' [-Werror,-Wsizeof-array-argument]
int len = (sizeof(myArray) / sizeof(myArray[0]));
^
prog.cpp:11:17: note: declared here
int sumEven(int myArray[])
^
1 error generated.
I have experience with Matlab, Mathematica, and Python, and so my C++ formatting may be strange. Thanks for taking a look.
The problem is that when passed as arguments to a function, arrays decays to pointers to the first element, so the function
int sumEven(int myArray[]) { ... }
is actually equal to
int sumEven(int *myArray) { ... }
And taking the size of a pointer returns the size of the pointer and not what it points to.
If you need to know the size in the function, you should pass the number of elements as an argument:
int sumEven(int *myArray, size_t len) { ... }
Arrays decay to pointers when you pass them to a function. That means that the information regarding the size of the array is lost.
This means that (sizeof(myArray) / sizeof(myArray[0])) will not do what you want in this context, because here myArray is a pointer.
The canonical solution is to add another parameter representing the array size, and use that instead. This is the approach used in C.
In C++, however, you should probably be using std:: vector, unless you have a specific reason to stick with arrays, which are notoriously error-prone.
I'm a novice programmer trying to get a head start on some classes before the summer semester starts, and I've run into this problem while trying to create a Quick Union algorithm in C++.
I've been trying to figure out why my program creates two identical arrays, despite having two separate for loops designed to create two different arrays. Whenever my program runs to completion and prints id[] and sz[], it always outputs 1 as the element at every index in both arrays.
class quickUnionUF{
private:
int id[];
int sz[];
int root(int);
public:
quickUnionUF(int, int);
bool connected(int, int);
void unionPoint(int, int);
void print();
};
quickUnionUF::quickUnionUF(int n, int b){
id[n];
sz[b];
for(int i=0;i<n;i++){
id[i] = i;
}
for(int j=0;j<b;j++){
sz[j] = 1;
}
}
For example, if I create quickUnionUF(5, 5);
id[] should now contains elements:
0, 1, 2, 3, 4
And sz[] contains elements:
1, 1, 1, 1, 1
However, the program creates an array sz[] AND array id[] with elements:
1, 1, 1, 1, 1
Any thoughts as to why this is happening?
Standard C++ does not have sizeless array members.
Use std::vector<int> as dynamically sized arrays in C++.
#include <vector>
class quickUnionUF{
private:
std::vector<int> id;
std::vector<int> sz;
int root(int);
public:
quickUnionUF(int, int);
bool connected(int, int);
void unionPoint(int, int);
void print();
};
quickUnionUF::quickUnionUF(int n, int b)
: id(n)
, sz(b)
{
for(int i=0;i<n;i++){
id[i] = i;
}
for(int j=0;j<b;j++){
sz[j] = 1;
}
}
Your code hints at a two very important mistakes:
C++ does not work like Java. int id[] is not an reference to an array of arbitrary size on the garbage collected heap. It is instead a member array of undefined size used to implement dynamic arrays (and similar features) in C99. You should never use this syntax unless you know exactly what you are doing, because it is almost guaranteed to be wrong otherwise.
id[n] does not allocate an array at all. Instead it just indexes id and discards the result.
Listen to your compiler!
First, your code should not compile due to the fact, that only the last member of a struct may be a flexible array type. In fact clang howls:
main.cpp:53:9: error: field has incomplete type 'int []'
int id[];
MSVC howls:
1>main.cpp(54): error C2229: class 'quickUnionUF' has an illegal zero-sized array
And g++ only warns (well, g++ is strange in what it accepts sometimes):
main.cpp:53:12: warning: ISO C++ forbids zero-size array ‘id’ [-Werror=pedantic]
int id[];
Note: g++ is wrong in compiling this, even if one allows flexible array members. This is defined in C99 6.7.2.1§16 and C11 6.7.2.1§18 both of which begin with (emphasis is mine):
As a special case, the last element of a structure with more than one named member may
have an incomplete array type; this is called a flexible array member. [...]
What is happening?
Well, assuming you got your code to compile anyway, it basically means the following:
Create an object with the alignment of integers, but NO elements at all. Take a peek at the following test program:
quickUnionUF q;
::std::cout << sizeof(quickUnionUF) << "\n";
::std::cout << &q << "\n" << &q.id[0] << "\n" << &q.sz[0] << "\n";
The only compiler that managed to compile this at all (gcc 4.9.0) gave the following result:
0
0x7fff1bf6274c
0x7fff1bf6274c
0x7fff1bf6274c
So, this is a zero byte object (yes, this is illegal C++, since every C++ object has a size > 0) and the first element of each array is at the same position (OUTSIDE YOUR OBJECT!). Remember, you declared id and sz to have zero elements!
Therefore, you are writing to the same arbitrary position. You can consider this the extreme case of a buffer overflow: By writing 5 integers to a zero size buffer, you are overflowing from the first zero size buffer through the second zero size buffer into memory totally not under your control.
This also explains your observed result: The second loop simply overwrites what the first did (and it still does it by corrupting your stack).
How do I fix this?
Just use a vector. You can tell it how big you want it and you can ask it to tell you when you are indexing to some position that is not yours.