I am trying to create a 2D array by a for loop but I get some garbage random numbers
code:
unsigned int i, j;
int matrix[10][10];//={{},{}};
for (i = 0; i < sizeof(matrix[i])/sizeof(int); i++) {
for (j = 0; j < sizeof(matrix[j])/sizeof(int); j++) {
cout <<matrix[i][j] << " " << flush;
}
cout << endl;
}
and when I change cout part to the following
cout <<matrix[i][j] = {{i},{j}} << " " << flush;
I get an error.
how can I make it?
Thank you in advance.
The dimension of an array is how many indices are used to access it, which is different than the size of a dimension (how many elements are in a row of the dimension), which is different than the size of an array or the number of elements in the complete array.
With what you have written, you are writing a 2-dimensional array of 10 rows, each containing 10 elements for a total size of 100 elements.
If you want to do an initializer list in that syntax, you must specify each row and each element in nested braces. You have one top level set of braces for the total array, then a set of braces for each sub-array. You can do this with curly braces enclosing each row, specifying each element as a comma separated list:
unsigned int i, j;
int matrix[10][10] = {{1,2,3,4,5,6,7,8,9,10},
{1,2,3,4,5,6,7,8,9,10},
{1,2,3,4,5,6,7,8,9,10},
{1,2,3,4,5,6,7,8,9,10},
{1,2,3,4,5,6,7,8,9,10},
{1,2,3,4,5,6,7,8,9,10},
{1,2,3,4,5,6,7,8,9,10},
{1,2,3,4,5,6,7,8,9,10},
{1,2,3,4,5,6,7,8,9,10},
{1,2,3,4,5,6,7,8,9,10}};
EDITED: The expression sizeof(matrix[i]) gives the size of the array as 40 because the compiler is able to figure that out at compile time, but it can be risky to rely on this since if you change it to a pointer to an array or the array is passed as a parameter to a function, it will give the size of the pointer instead of the array (as explained here: How do I determine the size of my array in C?). It would be better to display the array like this with the known length:
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
cout <<matrix[i][j] << " " << flush;
}
cout << endl;
}
Usually, for safety and convenience in changing, you can define the size using a macro like this:
#define ROWS 10
#define COLS 10
int matrix[ROWS][COLS] = ...;
then
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
cout <<matrix[i][j] << " " << flush;
}
cout << endl;
}
This way, if you decide to change the size of the matrix in the future, you only change the number in one place, the macro definition, instead of hunting through the code looking for each individual constant (especially with duplicate constants of 10, you might miss one or change an extra one that meant something else, which would cause problems somewhere else).
Related
Given a one-dimensional array with n integers and a whole number A,
list how many elements are larger than A
and build an array with these elements.
I'm having problems with the last part.
The answer is almost already in the question
(giving it here, assuming that the question is really as simple as it confusingly seems to me):
count the relevant elements, print/"list" that number
create a new std::array of that size
(consider asking whether using a std::vector is an option, it would allow doing this in a single pass)
(explicitly do NOT attempt to use the non-C++ construct of C-style VLA, variable length arrays, like std::cin>>n; int NewArray[n];)
go through the input array again and copy the relevant elements to the new array
count indexes in both arrays separatly, because the index in the first array will soon be larger than the index into the new array
Note:
I intentionally do NOT provide code, because I feel that the compromise described here should be applied: How do I ask and answer homework questions?
First you have to create two arrays (if you can use std::vectors, i think they will work nicely in this scenario) - first one as a base, and the second one for storing values larger than A.
Get input of A and n.
Use a for loop to put n values into the base array.
Use a for loop to check if baseArray[i] is bigger than A, if true - put baseArray[i] into the second array (if youre using std::vectors do it by push_back()).
Display the number of values higher than A by secondArray.size().
Without using the std::vector:
#include <iostream>
using namespace std;
int main()
{
int n;
int A;
int howManyBiggerThanA = 0;
cin >> n;
cin >> A; //you haven't specified how the n and A are supposed to be implemented so ill assume its going to happen this way
int *array = new int[n]; //creating an array with n integers
array[0] = A; //assigning A to the array as specified in the question - "and a whole number A"
for (int i = 1; i < n; i++)
{
array[i] = i; //filling the array with n integers of value 1 to n-1 (u havent specified what values are supposed to be inside this array)
}
for (int i = 0; i < n; i++)
{
if (array[i] > A)
{
howManyBiggerThanA++; //determining how many values are bigger than A
}
}
int *arrayForBiggerThanA = new int[howManyBiggerThanA]; //creating an array for values that are bigger than A
int assistant = 0;
for (int i = 0; i < n; i++)
{
if (array[i] > A)
{
arrayForBiggerThanA[assistant] = array[i]; //filling the second array with elements that are bigger than A
assistant++;
}
}
cout << "How many elements bigger than A: " << howManyBiggerThanA << endl;
cout << "Values bigger than A: ";
for (int i = 0; i < howManyBiggerThanA; i++)
cout << arrayForBiggerThanA[i] << ", ";
delete[] array;
delete[] arrayForBiggerThanA;
return 0;
}
For this assignment, I need to make a sorted copy of an array the user has given values to. All of my code works as intended, except for this specific part. I need this function (sortedCopy) to print out the sorted version of their array, without actually changing the array itself. As far as I can tell, to do so I need to used a constant version of the array in the function so the prototype would be something like: int *sortedCopy(const int *array, int size), but all this does is give the error shown in the title. Specifically:
main.cpp:72:29: error: assignment of read-only location '*(array +
((sizetype)(((long unsigned int)i) * 4)))' array[i] = array[min]
and it does this error twice, except with array[min] = temp; at the end instead
This is the code used, with the relevant parts of main:
#include <iostream>
using namespace std;
int* sortedCopy(const int *array, int size) {
int i, j, min, temp;
for (i = 0 ; i < size - 1; i++) {
min = i;
for (j = i + 1; j < size; j++) {
if (array[j] < array[min]) {
min = j;
}
}
temp = array[i];
array[i] = array[min];
array[min] = temp;
}
cout << "Sorted array is: " << endl;
for(int i = 0; i < size; i++) {
cout << array[i] << " ";
}
cout << endl;
// Not sure if I need to return anything or not either
}
int main() {
cout << "Please enter the size of the array." << endl;
int arraySize;
int array[arraySize];
cin >> arraySize;
cout << "Please enter integer values until the array is filled." << endl;
for (int i = 0; i != arraySize; i++) {
cout << "Value " << (i + 1) << ": ";
cin >> array[i];
cout << endl;
sortedCopy(array, arraySize);
for (int i = 0; i != arraySize; i++) { // I want this part to print the
cout << array[i] << " "; // original array entered by the user
}
}
If I remove the const part of the function, it works totally fine, except it will print the sorted array after the function is called, instead of the original array.
Firstly, C/C++ is best read "top-down":
int arraySize;
int array[arraySize]; // arraySize is undefined here!!
cin >> arraySize;
On the second line, ArraySize, might be 1, or 0, or -1000. You haven't defined it until line 3.
Also, C++ doesn't allow you to allocate arrays of variable size (unless that size is const [ so it is known at compilation time]):
int array[4];
The above is fine. This helps the operating system know how much memory to provide for you on the stack (it needs to do this before your programme starts running).
const int arraySize = 4;
int array[arraySize];
Because the C++ compiler knows that arraySize is 4, it processes this just like the above code, so this is also fine.
So to handle arrays of genuinely variable length (length that depends on inputs), you need to first read the user inputs, then use dynamic allocation ("new", or a container that does dynamic allocation for you, like a vector).
As for the problem with "const", what I think that you need to understand here is that "const" is really just a promise from the programmer: The programmer is communicating to the compiler (and any programmers reading the code) that this data is not supposed to change. All the compiler does is check whether you keep your promise (or if you send it to another function / pointer that doesn't hold that promise). So by using "const" there is no work done being done for you to actually keep the data constant - just that it will complain if you don't do the work.
int* sortedCopy(const int *array, int size) {
Above you're flagging to the compiler that the sortedCopy function will keep the data in the array constant.
array[i] = array[min];
array[min] = temp;
And here (above) you are breaking that promise.
If you don't want to edit the original array, then the easiest solution is just to copy it before you send it to your sorting function.
I'm hoping someone can shed some light on where I am going wrong with pointers.. I've read countless web pages and tried various things but for some reason my code is returning jibberish (which I'm guessing may be the memory addresses instead of the data within my array). The purpose of the program is to create an array of 100 elements on the heap, pass this array by a pointer to a function (along with two integer variables start and end); a new array will be created on the heap (this comprises of a chunk of the original array using the start and end variables) and the pointer to this array is passed back to the main method so that the new array can be outputted. My problem is not only is the output seeming to be the location not the value, but also it seems 100 values are outputted not 20 as should be expected. I've spent hours trying to figure out where I have gone wrong and just when I think I understand the concept of pointers my faith is destroyed by red squigglies and incorrect outputs. Please HELP! My code is as follows:
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
double* getSubArray(double*, int, int);// Declare a function that will get the sub array
int _tmain(int argc, _TCHAR* argv[])
{
const int size = 100;// Declare the size of the array
double* pA;// Declare the variable to hold the pointers to the data in array
double* pB;
int start = 15;
int end = 35;
pA = new double[size];// Create space for the array
srand(clock());// Seed the program to the computers current time so that random gets a different set of random numbers everytime it is run
// Use a for loop to traverse through each element of the array (starting at index 0) placing a number defined by the random function that is no higher than 250
for (int i = 0; i < size; i++)
{
pA[i] = rand()%250;
}
cout << "An Array of 100 numbers is created and stored in the heap, these values are:" << endl;
// Output the Array for the user to see
for (int j = 0; j < size; j++)
{
// Place 10 numbers on each line
if (j % 10 == 0)
{
cout << endl;
}
cout << *(pA + j) << " ";
}
cout << endl << "The program will build a second array using the data between the indexes " << start << " & " << end << endl;
pB = getSubArray(pA, start, end);// Pass the data to the method
// Output second array for user to compare
for (int k = 0; k < size; k++)
{
// Place 10 numbers on each line
if (k % 10 == 0)
{
cout << endl;
}
cout << *(pB + k) << " ";
}
system("pause");
return 0;
}
double* getSubArray(double* pA, int start, int end)
{
double* pB = new double[end-start];// Declare space in the heap for the new array whoes size is the size of the criteria given
for (int i = 0; i < (end - start); i++)
{
for (int j = start; j < end; j++)
{
*(pB + 0) = pA[j];
}
}
return pB;
}
*(pB + 0) = pA[j];
That keeps writing to the first element of the array. Surely you want to write to each element in turn:
for (int i = start; i < end; ++i) {
pB[i-start] = pA[i];
}
or if you don't want to write your own loop
std::copy(pA+start, pA+end, pB);
Don't forget to delete[] everything you new[] or, to save mucking around with low-level memory management, use std::vector to manage the dynamic arrays for you.
I am trying to loop through the array and get the elements inside in C++. Here is my code:
int result;
int index_array [] = {11,12,13,14,15,16,17,18,19,20};
for (int count =0; count < index_array.length() ; count++){
if(count%2 == 0){
cout << "Elements at the even index are " << index_array[count] << endl;
}
}
If I change the for loop to:
for (int count =0; count < 10 ; count++){
There is no error because my array only consists of 10 items. But if I used the .length() method, there is an error which is expression must have a class type. I have no idea what is it, as in if it is in Eclipse, there contains a more detailed error description. What might be wrong?
Updated answer
for (int count =0; count < sizeof(index_array)/sizeof(index_array [0]) ; count++){
if((count+1)%2 == 0){
cout << "Elements at the even index are " << index_array[count] << endl;
}
}
You can't call length() on int index_array[], it is a primitive array, not an object.
You could call size(), if you have, for example vector<int> index_array.
There is not .length for a plain array in C++.
Instead use std::vector and you can use method size() :
std::vector<int> index_array {11,12,13,14,15,16,17,18,19,20};
for (int count =0; count < index_array.size() ; count++){
if(count%2 == 0){
cout << "Elements at the even index are " << index_array[count] << endl;
}
}
Also in your case, you can calculate the length of the array:
int length = sizeof(index_array)/sizeof(index_array[0]);
int index_array [] = {11,12,13,14,15,16,17,18,19,20};
This is not an object that you can invoke some length() method on. Instead, it's a regular array, just like in C.
You can do one of two things.
The first is to use one of the C++ collection classes such as std::vector (adjustable size) or std::array (constant size) with their size() methods:
// C++11 syntax
std::vector<int> index_array {11,12,13,14,15,16,17,18,19,20};
// Pre C++11 syntax
int ia_src[] = {11,12,13,14,15,16,17,18,19,20};
vector<int> index_array (ia_src, ia_src + sizeof (ia_src) / sizeof (*ia_src));
std::array<int,10> index_array = {11,12,13,14,15,16,17,18,19,20};
The second is to simply treat the array as an array, in which case the length of that array can be found with the expression:
sizeof (index_array) / sizeof (*index_array)
Just be aware that this only works for arrays. If you pass that array to a function, it will decay to a pointer to the first element and sizeof will no longer work as you expect. You need to get the size while it's still an array and pass that along with it.
Arrays in c++ are not object (classes) so they don't have neither methods nor attributes.
May be you can use the Array class instead and get the size like std::array::size()
I've just started learning C++ so I'm fairly sure the answer may be a simple one. As a test I'm just setting up an array and then wanting to print out the array by looping through it.
My code is below. It prints out my array as expected but then prints out a load of other numbers below it. What are these numbers and where are they coming from? I suspect that 'sizeof' isn't the best to use. All of the examples i've found are alot more complicated than I need. In any case I am interested to understand the extra numbers. Any insight available?
int age[4];
age[0]=23;
age[1]=34;
age[2]=65;
age[3]=74;
for (int i = 0; i <= sizeof(age); i++)
cout << age[i] << endl;
return 0;
...output:
23
34
65
74
4
2147307520
0
2293608
4198582
1
3084992
3085608
-1
2293592
1980179637
-725187705
-2
sizeof gives the size of an object in bytes. If the array elements are larger than one byte (as int usually is), the number will be larger than the array size.
One way to get the number of elements in an array is to divide by the size of an element:
for (size_t i = 0; i < sizeof(age)/sizeof(age[0]); i++)
std::cout << age[i] << '\n';
(note that you also need < rather than <=, or you'll still step off the end).
Another way is to pass a reference to the array to a function template, instantiated for the array size:
template <typename T, size_t size>
void print(T (&array)[size])
{
for (size_t i = 0; i < size; ++i)
std::cout << array[i] << '\n';
}
print(age);
Yet another way is to use a std::vector or std::array instead of a plain array:
std::array<int, 4> age;
age[0]=23;
age[1]=34;
age[2]=65;
age[3]=74;
for (size_t i = 0; i < age.size(); ++i)
std::cout << age[i] << '\n';
sizeof(age) == sizeof(int) * number_of_elements ==>
number_of_elements = sizeof(age) / sizeof(int)
Then your code becomes:
for (int i = 0; i < sizeof(age)/sizeof(age[0]); ++i)
cout << age[i] << endl;
In C++ you may write a function to calculate the size for you(doesn't work with dynamic arrays):
template <class T, std::size_t size>
std::size_t array_size( T(&arr)[size] )
{
return size;
}
If you are up to C++11, you could go with for-each loop:
for(int element : age){
....
}
Also, free-function form of std::begin and std::end can do the job:
for(auto b = std::begin(age); b != std::end(age); ++b){
....
}
Sould be i < 4 because sizeof(age) is 16 on a 32 bits machine.
sizeof(age) is the number of bytes of age, not the number of elements.
Divide it by the size of an element of age to get that:
for (int i = 0; i < sizeof(age) / sizeof(*age); i++)
cout << age[i] << endl;
Note: for dynamic arrays, you have to store the size of the array separately:
std::size_t size = 4; // size_t corresponds to maximum size an array can hold
int* age = new int[size];
for (int i = 0; i < size; i++)
cout << age[i] << endl;
The other numbers are garbage past the end of the array.
age[10] is undefined behavior, which is essentially garbage numbers.
Sizeof is age array is 16 bytes I.e. Sizeof(int) * 4. You need array length.
Since sizeof(age) returns 16, you have your 4 values plus 12 ones whose value comes from the memory that is right after your array. Values in those memory segment is random, depending on what has been stored there right before you launched your program. If you used a memory check tool, you would have had an error since this memory is probably not allocated for your program.
As the other ones said, you should probably giving the exact number of element in your array as an additional variable.
const int COUNT = 4;
int age[COUNT];
age[0]=23; age[1]=34; age[2]=65; age[3]=74;
for (int i = 0; i < COUNT; ++i)
{
cout << age[i] << endl;
}