Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Here is my code:
The marked line is giving the error.
class Student{
public:
//Student(string x, int y, string z[]);
void getinfo();
void printinfo();
private:
string name;
int numClasses;
string arr[numClasses]; // the error is here it's not allowing me to put numClasses as the size of
// the class
};
The size of the array must be a constant integral expression
You can do something like this:
class Student
{
public:
void getinfo();
void printinfo();
private:
string name;
static const int numClasses = 20;
string arr[numClasses];
};
Since, the array will be allocated at compile time, and so when the size is not a constant, the compiler cannot accurately determine its value and throws error.
if you want to use array with dynamic size, use vector.
Here,
1) Change size to const
2) or, use vector -> vector<string>arr;
Array should be constant here is some explanation that can help that I found in cpp website
The elements field within brackets [] which represents the number of
elements the array is going to hold, must be a constant value, since
arrays are blocks of non-dynamic memory whose size must be determined
before execution. In order to create arrays with a variable length
dynamic memory is needed
since you have got your answer already I am just going to include great information about arrays that other might benefit from.
in c++ correct way to declare an array of 10 integers for example can be done this way
int array[10];
if you know a head of time what values you want in the array you can just do it this way
int numbers [] = {13, 30, 50, 2, 5, 6, 70, 8, 9, 10};
"Pointer arithmetic" & regular arithmetic
Pointer arithmetic is a way of expressing evaluations it uses 2 stacks one for characters and one for numbers for example pointer arithmetic uses *(a+1)" where as regular arithmetic uses "a[i]"
both are the same
one of my professors talked a lot about arrays
and say array[i] = *(a+i)
what does that mean?
it basically means
if a[i] = a[0]
then in pointer arithmetic it is :
*(a+0);
and if a[i] = a[1]
then in pointer arithmetic it is :
*(a+1); and so on
basically I shared about 2 weeks of my data structure course :P
hope I was able to help
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
As the title suggests,
int [] a = new int[size];
constantly throws me an error.
I am not yet familiar with C++ so please help me tweak the code above to as closely similar to the syntax above (above was a given pseudo(?) code in a class) so I can create an array.
Thank you.
#include <iostream>
using namespace std;
// Test program
int main( )
{
int [] a = new int[10];
cout << a[0];
return 0;
}
Tried running the above code and it failed to compile.
new is for dynamic allocation (of an array on the heap in this case), and returns a pointer to the new array.
[] in the declaration are for declaring it to be a stack array (and the brackets belong the right side of the variable name).
So the two legal approaches your code is mixing would simplify to either:
int a[10]; // Declares a stack array of size 10
or:
int *a = new int[10]; // Dynamically allocates a heap array of size 10 and stores the pointer to it in `a`
The former is the better solution here (there's no benefit to a heap allocation for such a small array that is only used within the scope of this function, and it would require explicit delete[] a; later to properly clean it up).
That said, neither version initializes the values, so the contents of a[0] are uninitialized, and reading from them will get random garbage. Both versions can be changed to initialize the data with zeroes though, e.g.:
int a[10] = {0}; // Declares a stack array of size 10 and initializes to zero
or:
int *a = new int[10](); // Dynamically allocates a heap array of size 10 and stores the pointer to it in `a`, initializing to zero
Final note: Using raw new is generally frowned upon in modern C++. If you needed heap-allocated contiguous data storage, you're probably better off using a std::vector.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I have been trying to learn arrays and I can't seem to define an array.
const int size = 10;
??[size];
Can anybody spot my mistakes? Thank You.
To declare an array using a constant, you should use this syntax:
// constexpr is explicitly compile time constant
constexpr int size = 10;
int my_array[size]; // int array, can be changed to float
For dynamic array, use vector:
int size = ...;
std::vector<int> my_array;
array.resize(size);
You can also use modern statically sized array:
constexpr int size = 10;
std::array<int, size> my_array;
const int size = 10;
type array[size];
Is what you want. Substitute type for any type (i.e. int, float, bool etc.).
In this case, specifying array size using a const variable is valid, but there are many cases where it isn't. You'd probably want to learn the difference between const and constexpr.
Also, instead of learning by asking questions here, try finding a good c++ source: a book, online article series or a video tutorial. It'll definitely accelerate your education.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I programmed several years ago, in which I wrote everything in the main function instead of using classes and other functions so I'm pretty confused. I have a project that has a specified format, and the way the array is defined is confusing me. I initially thought that xArray was a dynamic array, but when I try to assign a size to it, it gives error E0513 "a value of type "int *" cannot be assigned to an entity of type Group1
Group1{
int x,y;
}
Group2{
int a,b;
Group1* xArray;
}
void main{
Group1 g1;
int length;
cout <<"enter the length"<< endl;
cin >> length;
g1.xArray = new int[length];
}
so basically, I have a few questions, 1. what exactly is xArray(pointer? array?) 2. if it is a dynamic array, can I assign a length to it (which would be an input variable) outside the class where it's defined?
Your issue is that you are attempting to assign an array of one type, to a pointer of another. Here is a simpler example:
struct OneInt {
int a;
}
...
OneInt *o = new int[5]; // This cannot work, int is not the same type as OneInt
OneInt *o = new OneInt[5]; // This will allocate memory for an array of type OneInt
But honestly, you should do neither. You are looking for a dynamically sized vector, so c++ helps you by providing std::vector:
Group2{
int a,b;
std::vector<Group1> xArray; // By using an array, the memory is initialized and
// handled automatically
}
Group2 g;
g.xArray.resize(5);
This way, we don't need to mess around with new and delete and we have better, exception safe, encapsulated code. This is a technique of modern c++ called Resource Aquisition is Initialization (RAII).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
The question is in the title:
What is int * a[][10];
Is it an array of pointers to arrays of int? I tried to youse the clockwise/spiral rule but I am not sure...
int * a[][10];
is an illegal declaration in C++, as the storage size isn't known. You need to initialize it with arrays of 10 pointers to int, like so:
int* a[][10] = {{nullptr}}; // initialize with one array, the latter consisting of null pointers
or, even simpler,
int* a[][10] = {{}};
Once initialized, it becomes an array of arrays-10 of pointers to int.
int *a[][10], is to be read as pointer to 2D array of undefined rows (by default I guess it is 0) and 10 columns,with data read out row-wise in memory layout.
But this declaration is only possible in C.
If we declare a 2D array namely int abc[10][10] then we can make 'a' to point this array 'abc'.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am using a c++ integer array (int *). I have number sets generated and placed into this array, such as 1, 0, 3, 4, 5. The array is allotted 16 characters by this method
int *arr = (int *)malloc(16).
I need to be able to loop through this array and use each number and tell how many numbers are in the array. To loop through each element in the array, I have tried two methods:
for(int i=0;i<sizeof(arr);i++) and for(int i=0;arr[i]!='\0';i++).
The problem with the first method is that sizeof returns 16, because thats how much space I allotted for that array. The second method is successful unless there is a 0 in the sequence. How should I go about looping through each element in the array without getting stuck on 0 or looping through all 16 slots?
Since you've used dynamic allocation for this "array" (block of memory), the dimension of the array is not known to the type system. That means you cannot use sizeof(arr). All you've done there is find the size of your int* (a pointer).
And, as you've discovered, trying to null-terminate this array is completely silly because 0 is a perfectly valid, sane integer value.
What you should do is one of the following:
Option 1
const unsigned int LENGTH = 16;
int* ptr = new int[LENGTH]; // (malloc is an ancient approach from C)
for (unsigned int i = 0; i < LENGTH; i++) {
// ...
}
delete[] ptr;
// here, I've remembered the block's size myself
Option 2
std::vector<int> vec(16);
for (auto myInt : vec) {
// ...
}
// here, the wrapper called "vector" knows its own size
Option 2a
If you just picked 16 arbitrarily to provide a maximum upper bound, and you don't always need 16 elements:
std::vector<int> vec; // this grows as needed
vec.push_back(1);
vec.push_back(0);
vec.push_back(3);
for (auto myInt : vec) {
// ...
}
Option 3
If the value 16 doesn't rely on user input or other runtime data, leave out the dynamic allocation:
std::array<int, 16> arr;
for (auto myInt : arr) {
// ...
}
Or, to go old-school:
int arr[16];
for (auto myInt : arr) {
// ...
}
Conclusion
It's hard to tell what you're trying to do, but I think you are trying to have a bunch of array elements, not all of which may be "used" at any one time, and somehow mark the "un-used" ones. In this case, you want to abandon that old-fashioned logic, and use option 2a above.
Bootnote
I've used some C++11 constructs here, namely std::array and the ranged-for loop. Replace the loops with more conventional equivalents as you required.
sizeof returns the types size in bytes, not the length of an array. So, to get method #1 to work, you'll have to store the length of the array.
You should use countof instead of sizeof:
template <typename T, size_t N> size_t countof( T (&array)[N] ){return N;}
I don't know exactly why it works (I mean I don't know how to write it if I loose it) but I use it (I will try to understand it - now!)
Another method I know better how to explain is using
sizeof(arr)/sizeof(int).
Avoid using "special case" values when you can. There are always causing problems.
There are already some very good answers written but I just wanted to add an ugly one:
If you want the size of the array in the way you write it
int *arr = (int*)malloc(16);
the size would depend on the size of an int on your system, it could be e.g 4 bytes per int so max 4 ints would fit in. In order to keep track of the size of what you have allocated you will need to manually enter the size in the allocated block e.g.
int n = 4;
int *arr = (int*)malloc((n+1)*sizeof(int));
*arr = 4;
then move the pointer
++arr;
whenever you need the size, check *(arr-1)
when you free the block make sure to use free(arr-1)
probably best to wrap them in some kind of function to hide the ugliness.
I really do not recommend this method since you are programming in C++, avoid malloc/free since they are not very C++ compatible, i.e. they know nothing about constructors, instead use new/new[]/delete/delete[] also vector<> is one of my favorite templates, once you know how to use that arrays will be a breeze.