I have successfully reversed a 1-D array but when I cout the contents, it prints out the contents then bunch of other numbers.
4
3
2
1
-858993460
-858993460
4
-858993460
-1021245226
12384668
3697177
1
14484784
14501672
-1021245434
0
Press any key to continue . . .
I can't tell why it's printing out those extra numbers. Below is my source code:
#include <iostream>
#include <array>
using namespace std;
void flipRow(int array[], int row) {
int temp;
for (int i = 0; i < sizeof(array)/2; i++) {
//cout << "Hi" << endl;
temp = array[i];
array[i] = array[row-1];
array[row-1] = temp;
row--;
}
}
int main() {
const int ROW = 4;
int array[ROW] = { 1, 2, 3, 4 };
flipRow(array, ROW);
for (int i = 0; i < sizeof(array); i++) {
cout << array[i] << endl;
}
system("pause");
return 0;
}
Are those addresses? Can someone tell why it's printing them out? Thank you.
Modify your for loop in main so the condition part of it becomes i < ROW and modify the for loop in flipRow so the condition part there reads i < row/2. sizeof operator returns the size of your array in bytes. You have four elements in your array and they are of type integer, which on your platform is 4 bytes, so your call to sizeof is returning 16.
Related
I have a variable k of type int to set the length of a dynamically allocated int array:
int *Numbers = new int[k];
But because of this I cannot iterate over the array, I get an error:
"no matching begin function was found required for this range-based for statement"
I also cannot get the length of the array using size();
Here's the complete code:
#include <iostream>
using namespace std;
int main()
{
int b, k;
cin >> b >> k;
int *Numbers = new int[k];
for (int i : Numbers) {// (There is a error)
}
for (int i = 0; i < size(Numbers); i++) {
}
}
Prefer using a std::vector instead of a std::array. (Like #tadman mentioned.)
Here is your code using std::vector instead:
#include <iostream>
#include <vector>
int main()
{
int b, k;
std::cin >> b >> k;
std::vector<int> Numbers(b,k); // Fills the vector "Numbers" with nth number of elements with each element as a copy of val.
for (int i : Numbers)
std::cout << i << std::endl;
for (int i = 0; i < Numbers.size(); i++)
std::cout << Numbers[i] << std::endl;
return 0;
}
Say I want 10 elements with the number 5.
Output:
10
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
Also consider not using namespace std;.
The simple and recommended solution is to use std::vector, however if you really want a dynamically allocated array and to use iterator like features on it, you can use iterator_range from boost library, which allows you to create an iterator range for it thus making it usable in range based for loops and in functions like std::size.
Live demo
#include <iostream>
#include<boost/range.hpp>
int main()
{
int k = 5;
int *Numbers = new int[k]{1,4,5,7,8};
auto arr = boost::make_iterator_range(Numbers, Numbers + k);
for (int i : arr) { //range based loop
std::cout << i << " ";
}
std::cout << std::endl << "Size: " << arr.size(); //print size
//or std::size(arr);
}
Output:
1 4 5 7 8
Size: 5
Range-based for loops work with arrays, but not work with pointers. The Actual issue is that arrays is actually a pointer and not an array.try to use simple array.
Using pointers is problematic for many reasons. The simple solution to your problem is to use a vector
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int b, k;
cin >> b >> k;
vector<int> Numbers(k);
for (int i : Numbers) {
cout << i << endl;
}
for (int i = 0; i < Numbers.size(); i++) {
cout << Numbers[i] << endl;
}
}
C array does not have default iterator and thus there is no begin() and end() functions that are used to iterate over array when you use statment like this:
for (int i : Numbers)
You can check range-for reference:
range_expression - any expression that represents a suitable sequence (either an array or an object for which begin and end member functions or free functions are defined, see below) or a braced-init-list.
Okay, so since the dynamic array does not have a default iterator, do not use the for-each loop, instead consider using the regular for loop.
Also, mind the the size function will not work for an array (or dynamic array) and you need to remember the size, since it's not possible to get the size from the pointer only. Hence, this code would work:
#include <iostream>
using namespace std;
int main()
{
int b, k;
cin >> b >> k;
int *Numbers = new int[k];
const int SIZE = k;
for (int i = 0; i < SIZE; i++) {
cout << i << ' ';
}
}
You need to dereference *Numbers by using the * if you want to iterate over the array because *Numbers is a pointer to an integer which points to the first element of your array.For Example :
#include <iostream>
using namespace std;
int main()
{
int k = 10;
int *numbers = new int[k];
//filling the array
for(int i = 0 ; i < k ; ++i) {
*(numbers + i) = i ;
}
//output array element
for(int i = 0 ; i < k ; ++i) {
cout << numbers + i << " is the address of "<<*(numbers + i) << endl;
}
return 0;
}
The output is :
0x6f1750 is the address of 0
0x6f1754 is the address of 1
0x6f1758 is the address of 2
0x6f175c is the address of 3
0x6f1760 is the address of 4
0x6f1764 is the address of 5
0x6f1768 is the address of 6
0x6f176c is the address of 7
0x6f1770 is the address of 8
0x6f1774 is the address of 9
Unfortunatly, you can't get the size of your array with *Numbers because it's not an array but a pointer.
This question already has an answer here:
Array not playing back properly inside function - bubble sort
(1 answer)
Closed 2 years ago.
I am learning bubble sort. In my output array, the numbers in my presort array output correctly, but the second time it outputs with the sorted numbers it omits the 0 in the 10. I get an output of: Before sort: Array = {10, 2, 3, 1} After sort: Array = {1, 2, 3, 1} Any ideas?
#include <iostream>
using namespace std;
void showArray(int sortMe[], int size);
int main()
{
int sortMe[4] = {10, 2, 3, 1}; // Original Array
int numElements = 4;
int temp; // For swapping
cout << "Before sort: ";
showArray(sortMe, numElements);
for (int i=numElements-1; i>0; i--) { // For loop1
for(int j=0; j<i; j++) {
// Checks if the value on left is bigger than the right
if(sortMe[j] > sortMe[j+1]) {
// If bigger swap values
temp = sortMe[j];
sortMe[j] = sortMe[j+1];
sortMe[j+1] = temp;
}
}
}
cout << "After sort: ";
showArray(sortMe, numElements);
}
void showArray(int sortMe[], int size) {
// Outputs array in format array = {num1, num2, etc.}
int i = 0;
cout << "Array = {";
for (int i = 0; i < size - 1; i++) {
cout << sortMe[i] << ", ";
}
cout << sortMe[i] << "}" << endl;
}
Your problem is not the sorting, but printing. You define i two times.
If you rewrite your for loop inside the print like this your problem is solved for (; i < size - 1; i++).
The way you've written it the last element is always the element at index 0 because of int i = 0; outside of the loop.
I have a uint8_t type array, 4x4 dimensions, I have use nested for loops to display the array, hex values are converted to hex string through sprintf().
void hexD(uint8_t state[4][4])
{
char x[2];
for(int i = 0; i < 4; i++)
{
cout << "\n";
for(int j = 0; j < 4; j++)
{
cout << j <<"\n"; //displays the value of j
sprintf(x, "%x", state[i][j]);
cout << x << "\t";
}
}
}
The problem is inner for loop which runs endlessly as value of j starts from 0 then 1 then 2 but instead of going to 3 it gets back to 1, j swaps between 1 and 2 thus the loop in running infinitely.
Any solutions to this.
Thanks.
Depending on your values in state[4][4], you're likely to end up
overflowing the x array (remember, you need a place for at most FF (2 chars) + 1 for the terminating '\0').
That's undefined behavior.
Fix it (char x[3];) and you should be fine. Here's an mcve:
#include <iostream>
#include <cstdint>
#include <cstdio>
using namespace std;
void hexD(uint8_t state[4][4])
{
char x[3];
for(int i = 0; i < 4; i++)
{
cout << "\n";
for(int j = 0; j < 4; j++)
{
cout << j <<"\n"; //displays the value of j
sprintf(x, "%x", state[i][j]);
cout << x << "\t";
}
}
}
uint8_t state[4][4]={
255,255,255,255,
0, 1, 2, 3,
0, 1, 2, 3,
0, 1, 2, 3,
};
int main()
{
hexD(state);
}
char x[2];
You only have two bytes for your "hex output" but no available space for a null character.
Writing more to an array with lesser capacity is undefined behavior.
Increase x array size to 3:
char x[3];
since as per sprintf:
A terminating null character is automatically appended after the
content.
Thus, you have a total of three characters including the null character.
Your x has only two spaces, but you are writing more characters into it. For example, a 0 in hex is "00", two characters plus a closing '\0'.
That overwrites neighboring memory, and your j happens to be there and get overwritten.
Increase the size of x[], and it should work.
So I am trying to solve this question:
Data is fed in the following input format. The first line contains two space-separated integers denoting the number of variable-length arrays, n, and the number of queries, q. Each line of the subsequent lines contains a space-separated sequence in the format
k Ai[0] Ai[1] … Ai[k-1]
where k is the length of the array, Ai, and is followed by the k elements of Ai. Each of the subsequent lines contains two space-separated integers describing the respective values of array number (ranging from 0 to n-1) and index in that particular array (ranging from 0 to ki) for a query. i.e, Given the following input:
3 3
3 1 2 3
5 4 5 6 7 8
4 9 10 11 12
0 1
1 3
2 0
This output is expected
2
7
9
I am basically a beginner in C++. This is the code I have tried but I feel the address at which each subsequent array is stored is giving me some problems
int main(){
int n, q;
scanf("%d %d", &n, &q);
printf("n,q = %d, %d\n", n, q);
int* row[n];
for (int i = 0; i < n; i++){
int k;
scanf("%d", &k);
printf("k = %d\n", k);
int col[k];
row[i] = col;
for (int j = 0; j < k; j++){
int elem;
scanf("%d", &elem);
printf("i,j,elem = %d, %d, %d\n", i, j, elem);
col[j] = elem;
cout << "address is " << &(col[j]) << "\n";
}
}
for (int query = 1; query <= q; query++){
int i, j;
scanf("%d %d", &i, &j);
int answer;
answer = *(row[i] + j);
printf("row[%d][%d] is %d\n", i, j, answer);
cout << "address is " << &answer << "\n";
}
return 0;
}
And this is the output produced:
n,q = 3, 3
k = 3
i,j,elem = 0, 0, 1
address is 0x7ffe236edb70
i,j,elem = 0, 1, 2
address is 0x7ffe236edb74
i,j,elem = 0, 2, 3
address is 0x7ffe236edb78
k = 5
i,j,elem = 1, 0, 4
address is 0x7ffe236edb60
i,j,elem = 1, 1, 5
address is 0x7ffe236edb64
i,j,elem = 1, 2, 6
address is 0x7ffe236edb68
i,j,elem = 1, 3, 7
address is 0x7ffe236edb6c
i,j,elem = 1, 4, 8
address is 0x7ffe236edb70
k = 4
i,j,elem = 2, 0, 9
address is 0x7ffe236edb60
i,j,elem = 2, 1, 10
address is 0x7ffe236edb64
i,j,elem = 2, 2, 11
address is 0x7ffe236edb68
i,j,elem = 2, 3, 12
address is 0x7ffe236edb6c
row[0][1] is 32766
address is 0x7ffe236edbcc
row[1][3] is 32766
address is 0x7ffe236edbcc
row[2][0] is 3
address is 0x7ffe236edbcc
Basically, I find that the array addresses are overlapping. Also, The answer computation by dereferencing is resulting in unexpected outputs. Any explanation to the mistakes made here would be appreciated.
Here is a major problem:
for (int i = 0; i < n; i++){
...
int col[k];
row[i] = col;
...
}
The variable col has its scope only inside the loop. Once the loop iterates the variable cease to exist. Storing a pointer to it will lead to undefined behavior when you try to dereference the pointer.
The simple solution is probably to dynamically allocate memory for col using malloc.
Missed that the question was tagged C++, and confused because the source doesn't actually use any C++-specific code. This kind of makes it worse since variable-length arrays are not part of C++. Some compilers have it as an extension, but you should not use it when programming in C++.
Instead you should be using std::vector and then you can easily solve your problem without your own dynamic allocation. Then you can make row a vector of vectors of int and col a vector of int, and then the assignment will work fine (if row have been set to the correct size of course).
An easy way to use C++ without getting too many memory management bugs is to use standard library types. Leave the bare metal stuff to the poor C guys who do not have that ;)
So instead of meddling with new[] and delete[], use types like std::vector<> instead.
The "modern C++" version below uses iostream for no good reason. Old stdio.h is sometimes the preferred choice and so is sometimes iostream. And sometimes it is just a matter of style and taste.
#include <vector>
#include <iostream>
#include <fstream>
typedef struct Q
{
int iArray;
int iIndex;
} Q_t;
typedef std::vector<std::vector<int> > Data_t;
typedef std::vector<Q_t> Query_t;
bool Load(Data_t& data, Query_t &queries, std::istream& is)
{
size_t ndata = 0;
size_t nqueries = 0;
is >> ndata;
is >> nqueries;
data.resize(ndata);
queries.resize(nqueries);
for (size_t d = 0; d < ndata; d++)
{
size_t l = 0;
is >> l;
data[d].resize(l);
for (size_t i = 0; i < l; i++)
{
is >> data[d][i];
}
}
for (size_t q = 0; q < nqueries; q++)
{
is >> queries[q].iArray;
is >> queries[q].iIndex;
}
return true;
}
int main(int argc, const char * argv[])
{
std::ifstream input("E:\\temp\\input.txt");
Data_t data;
Query_t queries;
if (Load(data, queries, input))
{
for (auto &q : queries)
{
std::cout << data[q.iArray][q.iIndex] << std::endl;
}
}
return 0;
}
The mistake is, you have used 'col' array which loses its scope after completion of for loop. The way you can fix this is by either using dynamic memory allocation or by declaring it outside the for loop
Hope the below code will help you get an idea :)
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n, q;
cin >> n;
cin >> q;
int* row[n];
int* col;
for(int i=0; i<n; i++)
{
int k;
cin >> k;
col = new int[k];
row[i] = col;
for(int j=0; j<k; j++)
{
cin >> col[j];
}
}
for(int query=0; query<q; query++)
{
int i,j;
cin >> i;
cin >> j;
cout << row[i][j] << endl;
}
delete[] col;
return 0;
}
My goal is to read in a file at the command line, which is to be an adjacency matrix representation of a directed graph, and store the values in a 2D array. My plan is to read the number of integers on a line and use that as the size for my array(i.e. a 5 line input, with 5 integers per line would mean i would create a 5 x 5 array). However, to initialize an array, a constant value is needed, and counting the integers per line and storing it in a variable to use as my size parameter, does not allow me to create the array.
Sample input:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
Code:
#include <iostream>
#include <sstream>
#include <fstream>
using namespace std;
int main(int argc, char **argv)
{
string currentLine;
int i, m = 0;
int count;
ifstream input(argv[1]);
int storage[10000];
printf("Original matrix: \n" );
if(input.is_open())
{
while(getline(input, currentLine))
{
istringstream iss(currentLine);
count = 0;
while(iss >> i)
{
if(iss.eof())//at end of each line, ends loop
{
count++;
storage[m] = i;
m++;
printf("%d \n", i);
break;
}
else
{
count++;
storage[m] = i;
m++;
printf("%d ", i);
}
}
}
}
int **matrix;
matrix = new int*[count];
for(int y = 0; y < count; y++)
matrix[y] = new int[count];
for(int r = 0; r < count; r++)
for(int c = 0; c < count; r++)
matrix[r][c] = storage[r+c];
printf("first = %d ", matrix[0][0]);
system("PAUSE");
return 0;
}
Based on my input, I should create a 5 x 5 array. But the line
int matrix[count][count];
Gives me an error saying that the "count" size parameter should be a constant. Is my way of counting the size of the input to use an invalid way of doing this, or is there a way to create a constant to use as my size param?
Instead of using 2D native C++ arrays, consider using a vector of vectors.
#include <vector>
#include <iostream>
int main() {
using namespace std;
int count = 5;
// create a matrix of 'count' rows by 0 columns
vector<vector<int>> matrix(count);
// resize the column count for each row
for (auto& r : matrix)
r.resize(count);
// use it just like an array
for (int i = 0; i < count; ++i)
matrix[i][i] = i;
for (int r = 0; r < count; ++r) {
for (int c = 0; c < count; ++c)
cout << matrix[r][c] << ' ';
cout << endl;
}
}
you will need to use a dynamic array
int *myArray; //Declare pointer to type of array
myArray = new int[x]; //use 'new' to create array of size x
myArray[3] = 10; //Use as normal (static) array
...
delete [] myArrray; //remeber to free memeory when finished.
http://www.cplusplus.com/forum/beginner/1601/
http://www.cplusplus.com/doc/tutorial/dynamic/
You are not going to get a 2-D array. You will have to work with Array of Array.
If you are willing to work with dynamic allocations, please do something like this:
int *myArray = new int [count]; // variable length array can get you into trouble here,
// if you are not careful as the inner dimension needs
// to be freed before the array goes out of scope.
for (/*iterate from 0 count*/) {
myArray[i] = new int [count];
}
myArray[m][n] to give you a semblance of what you wanted.