I am having trouble using a function.
I have two functions.
createTwoDArray: prompts user for row and column sizes, creates a new 2D array and returns it while also modifying the row and column variables passed to it.
printTwoDArray: should take in a 2d array and print everything. However, when calling this function, segmentation fault occurs immediately. Not one line of code inside the function is called even.
Thank you :)
int column, row;
char** createTwoDArray(int& column, int& row) {
int min, max, i, j;
cout << "\nPlease enter row size:";
cin >> i;
row = i;
cout << "\nPlease enter column size:";
cin >> j;
column = j;
char** dynamicArray2 = new char*[column];
for(i = 0; i < row; i++) {
dynamicArray2[i] = new char[column];
for(j = 0; j < column; j++) {
dynamicArray2[i][j] = '\0';
}
}
return dynamicArray2;
}
void printTwoDArray(char** array, int row, int column) {
//
}
//
char** array2 = new createTwoDArray(column, row)
printTwoDArray(array2, column, row); //this causes the segmentation error
//
There are two errors: 'column' was used to allocate rows, and row and column were mixed up when calling printTwoDArray().
Here is the fixed code. It runs fine in Visual C++.
#include "pch.h"
#include <iostream>
int column, row;
char** createTwoDArray(int& column, int& row) {
int min, max, i, j;
std::cout << "\nPlease enter row size:";
std::cin >> i;
row = i;
std::cout << "\nPlease enter column size:";
std::cin >> j;
column = j;
// *** Use row, not column to allocate the number of rows.
char** dynamicArray2 = new char*[row];
for (i = 0; i < row; i++) {
dynamicArray2[i] = new char[column];
for (j = 0; j < column; j++) {
dynamicArray2[i][j] = '\0';
}
}
return dynamicArray2;
}
void printTwoDArray(char** array, int row, int column) {
printf("\nPrinting %d rows:\n\n", row);
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
printf(" %2d", array[i][j]);
}
printf("\n");
}
}
int main()
{
//
char** array2 = createTwoDArray(column, row);
// Pass row and column in the right order!
printTwoDArray(array2, row, column);
//
return 0;
}
Related
My task is to create a function that adds a row to a 2d Array everytime that a user asks to. For simplicity, I have a default row value to start with and a column value that should be kept. This task can be referenced to a bookshelf. Once a certain amount of books or on that row of the bookshelf, then move to the next row and begin placing books there.
Additionally, how should I free the program once a new row is created?
I am a new programmer and do apologize if my question sounds dumb. Thanks in advance!
Attached is what I have so far.
#include <iostream>
#include <string>
using namespace std;
int **addRows(int row, int cols, int values)
{
// Declare a 2d Array
int **twoD;
twoD = new int *[row];
// Fill each row with a column
for (int i = 0; i < row; i++)
{
twoD[i] = new int[cols];
}
// Fill each row, column with value
for (int i = 0; i < row; i++)
{
for (int j = 0; j < cols; j++)
{
twoD[i][j] = values;
}
}
// Return the 2d array
return twoD;
}
int main()
{
int **twoD;
int row = 1;
int cols = 5;
int values = 1;
int userInput;
// Call the function with 3 parameters by assigning the returned array to twoD
twoD = addRows(row, cols, values);
cout << "Do you want to add a row? 1 for yes, 0 for no, -1 to exit";
cin >> userInput;
while (userInput != -1)
{
if (userInput == 1)
{
twoD = addRows(row, cols, values);
}
else
{
// Print out each value in the 2d Array to console
for (int i = 0; i < row; i++)
{
for (int j = 0; j < cols; j++)
{
cout << twoD[i][j];
}
cout << endl;
}
// Free the memory
for (int i = 0; i < row; i++)
{
delete (twoD[i]);
}
delete (twoD);
}
cout << "Do you want to add a row? 1 for yes, 0 for no, -1 to exit";
cin >> userInput;
}
}
Your code is missing the following lines:
//remove memory allocation of array of columns for each row
for (int i = 0; i < row; i++) {
delete[] twoD[i];
}
//remove memory allocation of array of rows
delete[] twoD;
//increase the amount of rows in our new twoD matrix
row++;
in this section:
if (userInput == 1)
{
//right here
twoD = addRows(row, cols, values); //call addRows to generate the new twoD matrix with the increased row count
}
I was making a cpp program in which it takes two input from the user which determine the size of the 2d array and pass the values to the mat class constructor and dynamically create an array of the user's defined size. But, I don't know why it is not working and showing segmentation fault
#include<iostream>
using namespace std;
class mat{
int **a;
int r, c;
public:
mat(int row, int col){
r = row;
c = col;
for(int i = 0; i < r; i++){
*a = new int[r];
*a++;
}
}
void input(){
for(int i = 0; i < r; i++){
for(int j = 0; i < c; j++){
cin >> a[i][j];
}
}
}
void display(){
for(int i = 0; i < r; i++){
for(int j = 0; i < c; j++){
cout << a[i][j] << "\t";
}
cout << endl;
}
}
};
int main()
{
int r, c;
cout << "enter row :";
cin >> r;
cout << "enter column :";
cin >> c;
mat m(r, c);
m.input();
cout << "array \n";
m.display();
}
I can feel that the issue is with the for loop in the constructor or maybe I am doing it wrong.
The class contains several errors.
The variable a is never initialized. When we try to address the memory pointed to by a we get a segmentation fault. We can initialize it like this a = new int*[r]
We should not change where a point's to, so don't use a++. Otherwise a[i][j] will not refer to the i'th row and the j'th column. We would also want to release the memory at some point.
The inner loop for the columns for(int j = 0; i < c; j++) once entered will never terminate and will eventually produce a segmentation fault. We need to change i < c to j < c.
If we fix these errors, it looks like this:
class mat {
int** a;
int r, c;
public:
mat(int row, int col) {
r = row;
c = col;
a = new int*[r];
for (int i = 0; i < r; i++) {
a[i] = new int[c];
}
}
void input() {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
cin >> a[i][j];
}
}
}
void display() {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
cout << a[i][j] << "\t";
}
cout << endl;
}
}
};
I am trying to sort a two dimensional dynamic array when row 1 is for product ID and row 2 is for the product price. I want to sort by product ID, and have the results displayed formatted with width of 5. Here is my code:
This section is fine and does what I am looking for:
void readData (int**, int, int);
void printData(int**, int, int);
void sortbyPartID(int**, int, int);
int main()
{
int index;
int **PriceSheet, rows, columns;
cout << "Enter the number of Products, and then the number of values associated with the products: ";
cout << "For default values, enter 5 (FIVE ITEMS, and enter 2 (TWO Values: ID and PRICE). ";
cin >> columns >> rows;
cout << endl;
PriceSheet = new int* [rows];
for (int row = 0; row < rows; row++)
PriceSheet [row] = new int[columns];
readData (PriceSheet, rows, columns);
cout << endl;
printData(PriceSheet, rows, columns);
sortbyPartID(PriceSheet, rows, columns);
return 0;
}
void readData (int **p, int rowSize, int colSize)
{
for (int row = 0; row < rowSize; row++)
{
cout << "Row ZERO is the Product ID and Row 1 is the Product Price\n";
cout << "Enter " << colSize << " numbers for the row number " << row << ": ";
for (int col = 0; col < colSize; col++)
cin >> p[row][col];
cout << endl;
}
}
void printData (int **p, int rowSize, int colSize)
{
cout << "\n\nThese are the Products IDs and Prices as entered in the system:\n";
for (int row = 0; row < rowSize; row++)
{
for (int col = 0; col < colSize; col++)
cout << setw(5) << p[row][col];
cout << endl;
}
}
THIS SECTION IS WHERE I NEED HELP
It reads correctly and prints the unsorted array also correctly, but I cannot figure out a way to sort the array. Specifically speaking, I need help on the void sortbyPartID function. I would like to use bubble sort, and I cannot figure out how to get this function to work. Any help with the sorting function/algorithm would be greatly appreciated.
void sortbyPartID (int **p, int rowSize, int colSize)
{
int swap = -1;
int end = colSize;
int sortedID = **p;
cout << "\n\nThese are the Products sorted Products IDs:\n";
for (int counter = colSize -1; counter >= 0; counter --)
for (int index = 0; index < end ; index ++)
{
if (sortedID[index] > sortedID[index + 1])
{
swap = *sortedID[index + 1];
sortedID[index + 1] = sortedID[index];
*sortedID[index] = swap;
}
}
for(int index = 0; index < end; index++)
{
cout << sortedID[index] << ", ";
}
cout << endl;
end --;
}
When I run, I get some weird results on the last section. Maybe I am missing something simple, not sure.
We can also perform this using do-while as follows:
bool isSwaped;
do
{
isSwaped = false;
for (int index = 0; index < end - 1 ; ++index)
{
if (p[index][0] > p[index + 1][0])
{
int swap = p[index + 1][0];
p[index + 1][0] = p[index][0];
p[index][0] = swap;
isSwaped = true;
}
}
} while (isSwaped);
You can simplify the entire thing by using objects. Objects allow you to handle the related data in a sane fashion. Also highly recommend are vectors instead of C arrays.
struct Product {
int id;
int price;
vector<int> others;
}
You can then store your products in vector<Product> my_products; and then sorting everything with
std::sort(my_products.begin(), my_products.end(),
[](const Product& a, const Product& b) { return a.id < b.id; });
You can keep the existing input/output format, but place the values in the right place. This way it's almost impossible to mess up the attributes and everything is easy to work with.
int sortedID = **p; is not what you want, and should be removed. (I think you wanted int** sortedID = p;)
Your bubble-sort should be something like:
for (int counter = colSize -1; counter >= 0; --counter)
{
for (int index = 0; index < end - 1 ; ++index)
{
if (p[index][0] > p[index + 1][0])
{
// std::swap(p[index], p[index + 1]);
int* swap = p[index + 1];
p[index + 1] = p[index];
p[index] = swap;
}
}
}
Live Demo
So for some reason I keep getting a 'unhandled exception, would you like to break the code?' whenever i run this, like it thinks I'm going outside the array. Here's the whole code, and ill post the bit that it breaks at below:
Header file:
struct mult_div_values
{
int mult;
float div;
};
void create_table(mult_div_values ** table, int rows, int columns)
{
table = new mult_div_values * [rows];
for (int i = 0; i < columns; i++)
{
table[i] = new mult_div_values [columns];
}
}
void set_mult_values(mult_div_values ** table, int rows, int columns)
{
mult_div_values TableValues;
TableValues.div = 0;
for (int i = 0; i < rows; i++)
{
TableValues.mult = i+1;
table[0][i] = TableValues;
}
for (int i = 1; i < rows; i++)
for (int x = 0; x < columns; x++)
{
if (x == 0)
{
TableValues.mult = i + 1;
table[i][x] = TableValues;
}
else
{
TableValues.mult = (i+1) * (x + 1);
table[i][x] = TableValues;
}
}
};
void set_div_values(mult_div_values ** table, int rows, int columns)
{
mult_div_values TableValues;
for (float i = 0; i < rows; i++)
{
TableValues.div = i+1;
table[0][static_cast<int>(i)] = TableValues;
}
for (float i = 1; i < rows; i++)
for (float x = 0; x < columns; x++)
{
if (x == 0)
{
TableValues.div = i + 1;
table[static_cast<int>(i)][static_cast<int>(x)] = TableValues;
}
else
{
TableValues.div = (i+1) / (x + 1);
table[static_cast<int>(i)][static_cast<int>(x)] = TableValues;
}
}
};
Source file:
#include <iostream>
#include "mult_div.h"
using namespace::std;
struct mult_div_values;
int main()
{
mult_div_values ** table = 0;
int rows, columns, rowswanted, columnswanted;
cout << "How many rows?\n";
cin >> rows;
cout << "How many columns?\n";
cin >> columns;
cout << "Which row do you want?\n";
cin >> rowswanted;
cout << "Which column?\n";
cin >> columnswanted;
create_table(table, rows, columns);
set_mult_values(table, rows, columns);
set_mult_values(table, rows, columns);
cout << "Mult value: " << table[rowswanted][columnswanted].mult << endl << "Div value: " << table[rowswanted][columnswanted].div;
system("Pause");
}
And it breaks at:
void set_mult_values(mult_div_values ** table, int rows, int columns)
{
mult_div_values TableValues;
TableValues.div = 0;
for (int i = 0; i < rows; i++)
{
TableValues.mult = i+1;
table[0][i] = TableValues; }
as soon as i hit that last line, it gives me a error message. Any ideas?
You are iterating incorrectly in the function that creates your array:
void create_table(mult_div_values ** table, int rows, int columns)
{
table = new mult_div_values * [rows];
for (int i = 0; i < columns; i++)
// ^^^^^^^
{
table[i] = new mult_div_values [columns];
}
}
The loop should be over rows, not columns.
Also, in set:
void set_mult_values(mult_div_values ** table, int rows, int columns)
{
mult_div_values TableValues;
TableValues.div = 0;
for (int i = 0; i < rows; i++)
{
TableValues.mult = i+1;
table[0][i] = TableValues;
// ^^^
}
..
}
The i there corresponds to a column index, but you're iterating up to rows. So either that should be table[i][0] = TableValues or the loop should iterate over columns
There are likely more problems than just this, but the immediate issue is that in your create_table() method, you're passing the array pointer by value. As a result, the pointer to the 2d array that the client passes to create_table() remains NULL, and causes the crash when set_mult_values() is called.
If I may editorialize briefly, I would highly recommend simply stepping through this kind of code using a debugger before asking the question. Doing so, you would have seen the obvious NULL pointer being passed to set_mult_values().
Secondarily, consider using STL types instead of raw arrays for this kind of thing. It will make your life approximately nine-hundred times easier.
I have to create a program that allows a user to fill in a (partial) Latin Square of order 4. You can use 0's to represent empty cells. The user will give the number to place, the row and column. The number should only be placed if it does not violate the properties of a partial Latin square and it shouldn't rewrite numbers that have already been placed.
I have an matrix that is outputting all zeroes now. So next I have to replace each of these values by what the user is inputting. The problem is I don't know how to do this.
Here is my code:
#include <iostream>
using namespace std;
const int ORDER = 4;
void fill (int m[], int order);
void outputMatrix (int m[], int order);
void replaceValue (int m[], int order, int n, int row, int column);
int main(){
int matrix[ORDER];
int row;
int column;
int n;
fill (matrix, ORDER);
outputMatrix (matrix, ORDER);
do {
cout << "Enter the number to place, the row and the column, each seperated by a space: ";
cin >> n;
cin >> row;
cin >> column;
}while (n > 0 || n <= ORDER);
if (n <= 0 || n >= ORDER){
cout << "Thank you";
cout << endl;
}
return 0;
}
void fill (int m[], int order){
for (int i = 0; i < order*order; i++){
m[i] = 0;
}
}
void outputMatrix (int m[], int order){
int c = 0;
for (int i = 0; i < order*order; i++){
c++;
cout << m[i] << ' ';
if (c == order){
cout << endl;
c = 0;
}
}
cout << endl;
}
void replaceValue (int m[], int order, int n, int row, int column){
for (int i = 0; i < order; i++){
m[order] = m[row][column];
m[row][column] = n;
}
}
How do I replace values in a Matrix in C++?
If you have a matrix, matrix[row][col] = value; would do the trick. However, I see that you allocate a single array. Make sure you look at this.
EDIT:
I looked closer at you code and you are doing some things wrong.
First:
matrix[ORDER]
will create a single array of ORDER values. If you want and ORDER by ORDER matrix try:
matrix[ORDER][ORDER]
Second:
You are calling:
void fill (int m[], int order){
for (int i = 0; i < order*order; i++){
m[i] = 0;
}
}
with an of size 4 and order == 4. This will loop outside the array and give you problems.
Try something like:
matrix[ORDER][ORDER];
for (int row = 0; row != ORDER; ++row)
{
for (int col = 0; col != ORDER; ++col)
{
matrix[row][col] = 0;
}
}
Hope this helps.
You can't really write arr[i][j] if arr is defined as arr[]. There's no information about the length of the row (how many columns there are).
You could use arrays of type arr[][4], and write your functions like so:
// The & is to pass by reference.
void print(int (&arr)[][4], int length)
{
for(int i = 0; i < length; i++) {
for(int j = 0; j < 4; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
But in my opinion for a low-order multidimensional array like this one, using a typedef for a vector of vectors is the better option:
typedef vector<vector<int> > Matrix;
void print(Matrix& arr)
{
for(int i = 0; i < arr.size(); i++) {
for(int j = 0; j < arr[i].size(); j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
In either case, writing arr[i][j] = k will behave as you expect.
The easiest way to clear/zero your matrix is that:
memset( &matrix, 0, sizeof(matrix));
;-)