I have this function meant to initialize a multidimensional 2d (6x6) array to zero. I call the function in main using cout to test it and it outputs garbage. Please help. Thanks!
int** initializeArray(void)
{
typedef int* rollArray; //this line is actually outside of the function in my
//program
int i, j;
rollArray *m = new rollArray[6];
for (i = 0; i < 6; i++)
m[i] = new int[6];
for (i = 0; i < 6; i++)
for (j = 0; j < 6; j++)
m[i][j] = 0;
return m;
}
If the value 6 is known at compile-time, I would suggest using std::array in a nested fashion. For example:
#include <array>
#include <iostream>
int main()
{
std::array<std::array<int,6>,6> a = {0};
for (int i = 0; i < 6; ++i)
{
for (int j = 0; j < 6; ++j)
{
std::cout << a[i][j] << std::endl; // Prints 0.
}
}
return 0;
}
In fact, you won't even need to create a function to initialize your array. Declare your nested array and you are good to go. (If you don't know the dimension at compile-time, you could use std::vector in a similar fashion.)
The problem is with your test.
How can you mess up such a simple test? Just use:
int ** a = initializeArray();
int i,j;
for (i = 0; i < 6; i++) {
for (j = 0; j < 6; j++) {
cout << a[i][j] << " ";
}
cout << endl;
}
Related
How do I make a function with for loop to store a given range of numbers into an array, then call that function in main program and print out the stored elements inside of the array?
int main ()
{
testing(array, 20);
}
int testing(int array[], int k)
{
for (int i = 0; k < 20; i++)
{
array[k] = i;
k++;
}
for (int j = 0; j < 20; j++)
{
cout << array[j] << endl;
}
}
I get the error of, "testing has to return value", which I understand that I should of have return var; for example. However, I don't know how to return an array of given elements to print out all the elements with a for loop.
Your function and loop constructions are not carefully designed. You can use pointers instead of having to return an array.
I think this is what you are trying to do:
#include <iostream>
void testing(int* a, int k)
{
for (int i = 0; i < k; i++)
a[i] = i;
}
int main()
{
int a[20];
testing(a, 20);
// you can see that a's elements have changed outside the main (in testing)
for (int j = 0; j < 20; j++)
std::cout << a[j] << "\n";
return 0;
}
You don’t seem to ever execute the first loop. Your stop condition for your first loop is k < 20, but k already is 20.
Then on the second loop, the array just prints out the garbage that was previously saved at those memory locations.
I think what you meant to do was:
for (int i= 0; i < k; i++) {
array[i] = i;
}
for (int j = 0; j < k; ++j) {
cout << array[j] << endl;
}
If you wanted to print the array in main, you need to change the function a bit, by passing in a pointer to the array rather than the array itself.
Also, your main function never initialised an array to pass into your function.
int main (void) {
int a[20];
testing (a, 20);
return 0;
}
Finally, set the return type of the testing function to void.
void testing (int array[], int k);
All in all, it should instead look like this:
#include <iostream>
using namespace std; // I don't recommend doing this
void testing (int * array, const int k);
int main (void) {
const int size = 20;
int a[size] = {0};
testing (a, size);
for (int i = 0; i < size; ++i) {
cout << a[i] << endl;
}
return 0;
}
void testing (int * array, const int k) {
for (int i = 0; i < k; ++i) {
array[i] = i;
}
}
Below is my c++ code. I am trying to implement a selection sort using pointers (start and end). The code compiles, but I am getting a segmentation fault before it will sort the random generated list (currently only prints the random numbers).
Any help as to why this is and how to fix it would be greatly appreciated.
#include<stdio.h>
#include<stdlib.h>
#include <iostream>
using namespace std;
void selectionSort(int *start, int *stop) {
for (int i = *start; i < *stop - 1; ++i) {
int min = i;
for (int j = i + 1; j < *stop; ++j) {
if ((&start[0])[j] < (&start[0])[min])
min = j;
}
swap((&start[0])[i], (&start[0])[min]);
}
}
int main()
{
int size = 10;
int* data = new int[size];
for (int i = 0; i < size; ++i)
{
data[i] = rand() % size;
}
for (int k = 0; k < size; k++)
{
cout << data[k] << " ";
}
cout << endl;
selectionSort(data, data+size);
for (int j = 0; j < size; j++)
{
cout << data[j+1] << " ";
}
return 0;
}
The general logic in your function is in the right direction. However, you seem to be confused between values of the elements of the array and the indexing used to access the elements of the array.
The line
for (int i = *start; i < *stop - 1; ++i)
shows the first signs of the confusion.
You are initializing i with the value of the first element of the array and incrementing the value in the subsequent iterations of the loop. That is not correct. Incrementing the value of the first element of the array does not make logical sense.
*stop causes undefined behavior since stop points to a place one past the last valid element.
You need to use int* i, int* j, and int* min to properly sort the elements. That also means updating almost the entire function accordingly. Here's an updated function that works for me.
void selectionSort(int *start, int *stop) {
for (int* i = start; i < (stop - 1); ++i) {
int* min = i;
for (int* j = i + 1; j < stop; ++j) {
if (*j < *min)
{
min = j;
}
}
swap(*i, *min);
}
}
Also, the following lines in main are not correct. You end up accessing the array using an out of bounds index.
for (int j = 0; j < size; j++)
{
cout << data[j+1] << " ";
}
Replace them by
for (int k = 0; k < size; k++)
{
cout << data[k] << " ";
}
I am currently working on a program that prints a 5 variable truth table. I am using a 2d array. My code currently produces the table, but says it is corrupt and "the stack around the variable "table" was corrupted. Any help?
#include <iostream>
using namespace std;
int main() {
bool table[5][32];
for (int i = 0; i < 32; i++) {
for (int j = 0; j < 5; j++) {
table[i][j] = ((i >> j)& 1);
}
}
for (int i = 0; i < 32; i++) {
for (int j = 0; j < 5; j++) {
cout << table[i][j] << " ";
}
cout << endl;
}
return 0;
}
This is homework, so I would like to understand it, not just have an answer.
The index is wrong. Only table[0] to table[4] are available, so accessing table[5] to table[31] is illegal.
Try this:
#include <iostream>
using namespace std;
int main() {
bool table[32][5]; // swap 32 and 5
for (int i = 0; i < 32; i++) {
for (int j = 0; j < 5; j++) {
table[i][j] = ((i >> j)& 1);
}
}
for (int i = 0; i < 32; i++) {
for (int j = 0; j < 5; j++) {
cout << table[i][j] << " ";
}
cout << endl;
}
return 0;
}
There is attempt to read out of bound values from array.
If you need 5x32 matrix Use code below:
for (int i = 0; i < 5; i++) { // 32-> 5
for (int j = 0; j < 32; j++) { // 5->32
If you need 32x5 matrix then replace code below:
bool table[32][5]; //it was table[5][32];
I need to implement a 5x5 dynamic array where
every element in it is equal to the sum of its two indices. For example, the first element, at (0,0), has the value 0+0=0.
Here is my code:
# include<iostream>
using namespace std;
int main()
{
int size =5;
int *array=new int[size];
for (int i = 0; i < size; i++)
delete [] array;
return 0;
}
I need help to implement sum of index.
You need at first to implement a two-dimensional array.:)
Here you are.
#include <iostream>
int main()
{
const size_t N = 5;
int ( *array )[N] = new int[N][N];
for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ ) array[i][j] = i + j;
}
for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ ) std::cout << array[i][j] << ' ';
std::cout << std::endl;
}
delete [] array;
return 0;
}
And do not pay attention that the answer is down voted. There is nothing wrong with the answer. :)
Firstly, you should create a 2d-array, not just a array.
void foo() {
int **a = new int*[5];
for (int i = 0; i < 5; i++)
a[i] = new int[5];
}
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
a[i][j] = i + j;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++)
cout << a[i][j] << " ";
cout << endl;
}
for (int i = 0; i < 5; i++)
delete[] a[i];
delete[] a;
}
And, of course, don't forget to clear your memory)
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));