I am currently working on this code. But there are some problems. First of all, if I run this code, it says array size in new-expression must be constant. If I make the array arr[n], this error message does not appear. Also this code makes error message when it gets to the line cout << arr[i][j] << endl; saying that invalid types 'int[int]' for array subscript. I do not understand why this error message comes out because I made the array arr[n][n] not arr[n].
What I want to make with this code is showing the magic-square for n*n if I type in n in the argument line.
This is my main.cc
#include <iostream>
#include <cstdlib>
#include <cstring>
#include "magic_square.h"
using namespace std;
int main(int argc, const char** argv) {
int n = atoi(argv[1]);
int *arr = new int[n][n];
if (n % 2 == 0 || n < 3)
return 0;
else
magicSquare(n, arr);
for (int i = 0, j = 0; i < n, j < n; i++, j++)
cout << arr[i][j] << endl;
delete[] arr;
return 0;
}
This is my magic_square.cc. I did not add magic_square.h as it is only the declaration of the funtion void magicSquare(int n, int* arr).
#include <iostream>
#include "magic_square.h"
void magicSquare(int n, int* arr) {
for (int i = 0, j = n/2, num = 1; num <= n*n; num++) {
arr[i][j] = num;
if (num % n == 0) {
i++;
}
else {
i--, j++;
if (i < 0)
i = n - 1;
if (j > (n - 1))
j = 0;
}
}
}
~
Can anybody help me with this errors? Thanks in advance!
Take account that the for condition is just working because the two comma separated expressions are true at the same time.
for (int i = 0, j = 0; i < n, j < n; i++, j++)
That end condition is equivalent to only do the last test, since its result will be the result of the comma separated expression.
Probably you should have written this:
for (int i = 0, j = 0; i < n && j < n; i++, j++)
Related
I am trying to create my own solution for TwoSum leetcode problem. I am assigning the array with random numbers in between 0, 20. I'm trying to write a function to find all
unique number pairs of the array that adds up to the
target number. Then I just want to print the pairs and their indices.
I am getting an undeclared error when I try to add the index of j to my array but I dont know why.
Here is my code, I appreciate any help or advice.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int getPairsCount(int arr[], int n, int sum)
{
int indices[10];
// Consider all possible pairs and check their sums
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (arr[i] + arr[j] == sum)
indices[0] = i;
indices[1] = j; //error is caused by this line
cout << indices;
}
int main()
{
int sz = 20;
int randArray[sz];
for(int i=0;i<sz;i++)
randArray[i]=rand()%20; //Generate numbers between 0 to 20
int n = sizeof(randArray) / sizeof(randArray[0]);
int sum = 6;
cout << "The indices that add up to the target sum is: " << endl;
cout << getPairsCount(randArray, n, sum) << endl;
return 0;
}```
Here is your code with some brackets:
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (arr[i] + arr[j] == sum)
{
indices[0] = i;
}
}
indices[1] = j; //error is caused by this line
}
See the issue? You've indented indices[1] = j; which makes you think it's part of the "for j" loop, but it isn't. In older versions of the C++ this would have worked.
When I use an array, the following code works well. I tried to replace array with std::vector, but found that procedures often appear abnormalities, need to run more times. Anything I missed? I am using g++ 10.3.
#include <iostream>
#include <vector>
int main() {
int n = 3;
for (int k = 1; k <= 4; ++k) {
// int *A = new int[k]();
std::vector<int> A(k, 0);
int i = 0;
for (; i >= 0; A[i]++) {
for (int j = 0; j < k; ++j) {
std::cout << A[j] << " ";
}
std::cout << "\n";
for (i = k - 1; i >= 0 && A[i] == n - 1; i--)
A[i] = 0;
}
}
return 0;
}
In this for loop in its third part
for (; i >= 0; A[i]++) {
^^^^^^
the variable i can be equal to -1 after the inner loop
for (i = k - 1; i >= 0 && A[i] == n - 1; i--)
where the same variable i is used (for example when k is equal to 1).
So it is unimportant whether you are using a vector or an array. The program has undefined behavior.
Here is the code. I need to have fixed rows and cols that get filled in with random numbers when the matrix function is called. There needs to be 2 functions, one for displaying and 1 for randomizing.
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
const int ROWS = 10;
const int COLS = 8;
int matrix[ROWS][COLS];
void RandMatrix(int **arr, int row) {
for (int i = 0; i < row; i++)
for (int j = 0; j < COLS; j++)
*((*arr + i) + j) = rand() % 10;
}
void DisplayMatrix(int **arr, int row) {
for (int i = 0; i < ROWS; ++i) {
for (int j = 0; j < COLS; ++j)
cout << matrix[i][j];
cout << endl;
}
}
int main()
{
srand(time(NULL));
int matrix[ROWS][COLS];
for (int i = 0; i < ROWS; ++i) {
for (int j = 0; j < COLS; ++j) {
matrix[i][j] = -1;
}
}
int *ptr[ROWS];
int **arr = &ptr[0];
int row = 10;
for (int i = 0; i < ROWS; i++) {
ptr[i] = &matrix[i][0];
}
RandMatrix(arr, row);
DisplayMatrix(arr, row);
}
Main problem
The pointer arithmetic is wrong in the line
*((*arr + i) + j) = rand() % 10;
It needs to be
*(*(arr + i) + j) = rand() % 10;
It will be easier to just use:
arr[i][j] = rand() % 10;
Minor problems
You are passing arr as argument to DisplayMatrix but you are not using it. Instead, you are using matrix. It works ok by lucky coincidence. It will be better to not use arr in the function.
You are passing row as argument to DisplayMatrix but you are using ROWS in the for loop. Once again, it works because of lucky coincidence.
You pass arr to DisplayMatrix - but you don't actually use it there. Instead, the function prints the values in the global variable named matrix. But those values were never initalized - RandMatrix populates a different variable named matrix, the one local to main.
You are calling the DisplayMatrix function with arr as an argument but you are not using arr in it at all. Instead, you are using matrix.
In the DisplayMatrix function, change the following line:
cout << matrix[i][j];
to
cout << *((*arr + i) + j);
And it will work as intended.
I'm writing a program that is made of a function that takes in a 2d array, c0unts the evens in the array and returns the amount of evens in that array. The function isn't returning the value that i intend it to, which is 6. Sometimes I get 0, sometimes I get a number like 2147483646.
#include <iostream>
#include <array>
using namespace std;
const int MaxNumOfRows = 3;
const int MaxNumOfColumns = 2;
int Even(int A[MaxNumOfRows][MaxNumOfColumns], int length, int width)
{
int NumnberOfEvens = 0;
int i;
int j;
for (i = 0; i < length; length++)
{
for (j = 0; j < width; width++)
{
if (A[i][j] % 2 == 0)
{
NumnberOfEvens++;
}
}
}
return NumnberOfEvens;
}
int main()
{
//int output = 0;
int A[MaxNumOfRows][MaxNumOfColumns] =
{
{2,2},{2,4},{2,2}
};
Even(A, MaxNumOfRows, MaxNumOfColumns);
//output = Even(A, MaxNumOfRows, MaxNumOfColumns);
cout << Even(A, MaxNumOfRows, MaxNumOfColumns) << endl;
system("pause");
return 0;
}
Check those for loops, I imagine you want to be incrementing the variables ++i and ++j rather than width++ and length++.
With an example this trivial, I imagine stepping through the executing code and finding the problem in a debugger would be pretty straightforward...are you writing this using an IDE with a debugger?
You are not applying increment on loop variables ('i' and 'j') here. 'length' and 'width' are increasing (due to length++, width++) whereas 'i' and 'j' are not. So, loop won't stop and thus the garbage values.
for (i = 0; i < length; length++)
{
for (j = 0; j < width; width++)
{
if (A[i][j] % 2 == 0)
{
NumnberOfEvens++;
}
}
}
This must work.
for (i = 0; i < length; i++)
{
for (j = 0; j < width; j++)
{
if (A[i][j] % 2 == 0)
{
NumnberOfEvens++;
}
}
}
This is my program in C++, which accepts an 2D array a[m][n]. If an element a[i][j] is zero, then set all the ith row and jth column elements to zero.
This is code sample:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
class SetZero{
public:
static void setZero(int **, int , int);
};
void SetZero::setZero(int ** a, int m, int n){
int i, j, k;
int ** b = new int *[m]; //flags to identify whether set to zero or not.
for(i = 0; i < m; i++){
b[i] = new int[n];
for(j = 0; j < n; j++)
b[i][j] = 1;
}
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
if(a[i][j] == 0 && b[i][j]){//DUMP here. If I change it to (a+i)[j], then works.
for (k = 0; k < n; k++){
a[i][k] = 0;//but there is NO dump here. Weird!
b[i][k] = 0;
}
for(k = 0; k < m; k++){
a[k][j] = 0;
b[k][j] = 0;
}
j = n;//break. next row loop.
}
for(int i = 0; i < m; i++)
delete[] b[i];
delete[] b;
}
int main(){
int a[4][5];
srand(time(NULL));
for(int i = 0; i < 4; i++){//create an 2D array
for(int j = 0; j < 5; j++){
a[i][j] = rand() % 100;
cout << a[i][j] << " ";
}
cout << endl;
}
SetZero::setZero((int **)a, 4, 5);//type cast.
cout << endl;
for(int i = 0; i < 4; i++){//print result
for(int j = 0; j < 5; j++)
cout << a[i][j] << " ";
cout << endl;
}
return 0;
}
Environment: WIN8 Visual Studio 2012.
Edit:
The program can compile but cannot execute normally. It will stop when it reaches if(a[i][j] == 0 && b[i][j]){
The error message is:
Unhandled exception at 0x012875DD in CCLC.exe: 0xC0000005: Access
violation reading location 0x0000004B.
SetZero::setZero((int **)a, 4, 5)
a is not an array of pointers, it is simply a 2 dimensional array.
notice how the access violation is reading address 0x0000004B? that's 75, a number between 0 and 99 :) because you are treating a 2 dimensional array (which is just a one dimensional array with a neat way of accessing it) as an array of arrays, it is taking one of the values in your array (75) to be the address of a sub array, then trying to read the non existent array at address 75 (or 0x0000004B)
I suggest that you 'flatten' your arrays and work with them as one dimensional arrays, which I find simpler:
void SetZero::setZero(int * a, int m, int n){
int i, j, k;
int * b = new int [m*n]; //flags to identify whether set to zero or not.
for(i = 0; i < m; i++){
b[i] = new int[n];
for(j = 0; j < n; j++)
b[i*n+j] = 1;
}
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
if(a[i*n+j] == 0 && b[i*n+j]){//DUMP here. If I change it to (a+i)[j], then works.
for (k = 0; k < n; k++){
a[i*n+k] = 0;//but there is NO dump here. Weird!
b[i*n+k] = 0;
}
for(k = 0; k < m; k++){
a[k*n+j] = 0;
b[k*n+j] = 0;
}
j = n;//break. next row loop.
}
delete[] b;
}
int main(){
int a[4*5];
srand(time(NULL));
for(int i = 0; i < 4; i++){//create an 2D array
for(int j = 0; j < 5; j++){
a[i*5+j] = rand() % 100;
cout << a[i*5+j] << " ";
}
cout << endl;
}
SetZero::setZero(a, 4, 5);//type cast.
cout << endl;
for(int i = 0; i < 4; i++){//print result
for(int j = 0; j < 5; j++)
cout << a[i*5+j] << " ";
cout << endl;
}
return 0;
}
One suggestion about the SetZero(). There is a function called memset() which allows you to set all bytes to a specific value given a starting pointer and the range. This function could make your SetZero() function more cleaner:
void * memset ( void * ptr, int value, size_t num );
Fill block of memory. Sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char).
Parameters
ptr: Pointer to the block of memory to fill.
value: Value to be set. The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value.
num: Number of bytes to be set to the value, size_t is an unsigned integral type.
For example, the following code block from your program:
for (k = 0; k < n; k++){
a[i][k] = 0;//but there is NO dump here. Weird!
b[i][k] = 0;
}
can be achieved by memset in a cleaner way:
memset(a[i], 0, n * sizeof(int));
memset(b[i], 0, n * sizeof(int));