I would like to have an array int candidates[9][] where the first dimension is known (9) and the second, depends on the execution.
I found that a method to allocate the array was the following:
int *candidates[9]; /* first allocation at declaration */
for(int i=0;i<9;i++) candidates[i] = new int[6]; /* allocation at execution */
but when I use it like that, and I try to access to candidates[i][j], it doesn't work. I initialize candidate[i] with a function fun() that return and int[] of the right size, but the content of candidate[i][j] is wrong.
candidates[0] = fun();
I don't understand where I am wrong... Thank you for your help :-)
Try int *candidates[9] instead of int candidates[9][] and it should work.
Why dont you try vector template class from STL...code is more neater and comprehensive...
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> arrayOfVecs[9];
//use each array to put as many elements you want, each one different
arrayOfVecs[0].push_back(1);
arrayOfVecs[1].push_back(100);
.
.
arrayOfVecs[1].push_back(22);
arrayOfVecs[0].pop_back();
arrayOfVecs[8].push_back(45);
cout<<arrayOfVecs[1][0]<<endl;//prints 100
return 0;
}
WITH ARRAY OF POINTERS
int main()
{
int* arrayOfPtrs[9];
for(int index = 0;index<9;index++)
{
int sizeOfArray = //determine the size of each array
arrayOfPtrs[index] = new int[sizeOfArray];
//initialize all to zero if you want or you can skip this loop
for(int k=0;k<sizeOfArray;k++)
arrayOfPtrs[index][k] = 0;
}
for(int index = 0;index<9;index++)
{
for(int k=0;k<6;k++)
cout<<arrayOfPtrs[index][k]<<endl;
}
return 0;
}
Try int **candidates=0; followed by candidates = new int *[9] ;.
Code:
#include <iostream>
using namespace std;
int main(void)
{
int **candidates=0;//[9]; /* first allocation at declaration */
candidates = new int *[9] ;
for(int i=0;i<9;i++) candidates[i] = new int ; /* allocation at execution */
for( i = 0 ; i < 9 ; i++ )
{
for( int j = 0 ; j < 9 ; j++ )
{
candidates[i][j]=i*j;
cout<<candidates[i][j]<<" ";
}
cout<<"\n";
}
cout<<" \nPress any key to continue\n";
cin.ignore();
cin.get();
return 0;
}
Related
#include <iostream>
using namespace std;
struct stud
{
char name[10];
int id;
};
int input(stud a[], int size)
{
for(int i=1; i<=size; i++)
{
cout<<"name = ";
cin>>a[i].name;
cout<<"id = ";
cin>>a[i].id;
}
cout<<endl;
return 0;
}
int output(stud a[], int size)
{
for(int i=1; i<=size; i++)
{
cout<<"name = "<<a[i].name<<" ";
cout<<"id = "<<a[i].id<<" ";
}
cout<<endl;
return 0;
}
int copy(stud a[], stud x[], int size)
{
for(int i=1; i<=size; i++)
{
x[i].name=a[i].name;
x[i].id=a[i].id;
}
output(x,size);
cout<<endl;
return 0;
}
int main()
{
struct stud s[3], x[3];
input(s,3);
output(s,3);
copy(s,x,3);
return 0;
}
In this program the statement in function copy x[i].name =a[i].name; is not copying contents from 1 structure object to another. I have tried to put this statement in for loop for(int j=1;j<=10;j++) x[i].name[j] =a[i].name[j]; but still not working.
please suggest what should be changed or some alternatives for this.
i'll be very thankful to you for this.
regards,
umar
Either using a loop to copy each character in the name field or using thestrcpy function from <cstring> header works.
int copy(stud a[], stud x[], int size) {
for(int i = 1; i <= size; i++) {
// for(unsigned j = 0; j < 10; j++) {
// x[i].name[j] = a[i].name[j];
// }
strcpy(x[i].name, a[i].name);
x[i].id = a[i].id;
}
output(x, size);
cout << endl;
return 0;
}
But since you tagged this as c++, consider using std::string instead of a char array, unless you have a particular reason for using a char array. In that case x[i].name = a[i].name would have worked just fine and you could also use the standard algorithm library for copy. Also, using std::array instead of a raw C array for you "array of structures" might be a better option (does not degenerate into a pointer like a regular C array does).
Evrey single one of your loops is wrong, because in C++ arrays start at zero. So not
for(int i=1; i<=size; i++)
instead
for(int i=0; i<size; i++)
You cannot copy arrays by writing a = b;. Since your arrays are really strings there's a built in function strcpy to copy strings.
strcpy(x[i].name, a[i].name);
If you use = to copy struct, the char array inside that struct will be copied. You don't need to do anything more.
#include <iostream>
using namespace std;
typedef struct{
char name[10];
} type_t;
int main() {
type_t a = {"hihi"};
type_t b;
b = a;
a.name[0] = 'a';
cout<<a.name<<endl;
cout<<b.name<<endl;
return 0;
}
output:
aihi
hihi
ideone: https://ideone.com/Zk5YFd
I have this following code to sort number which I read from text file. My text file elements must be like this:
3 6
6
5
1
The first number (3) in the first column represents the number of elements that should I sort, the first number in second column represent the max number which I have to send via array which is 6 here.
And the number must be sorted is 6 5 1.
So this is my code but there is error says "invalid allocation size" and how to send max via array.
I need help please.
Here is my code:
// Read and Sort.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<fstream>
using namespace std ;
#include<time.h>
#include <string>
int Max ;
int number_of_items;
const int s= 22;
int arr[s];
int n=sizeof(arr)/sizeof(*arr);
class sort{
public:
int read_file()
{
int num = 0;
int x ;
char filename[50];
ifstream numbersfile ;
cout<<"Please enter the file name below"<<endl<<"_______________________________________________"<<endl;
cin.getline(filename,50);
cout<<"_______________________________________________"<<endl;
numbersfile.open(filename);
if(numbersfile.is_open())
{
for(int i =0;i<n;i++){
numbersfile>>arr[i];
Max=arr[0];
number_of_items=arr[1];
}
}
else{
cout<<"Failed To load requierd file"<<endl;
}
int arr2[s];
cout<<"The elements supposed to be sorted are:"<<endl<<endl;
for(int i =2;i<n;i++){
numbersfile>>arr[i];
cout<<arr[i]<<" "<<endl;
}
counting_sort(arr2,n);
return 0 ;}
int counting_sort(int arr[],int size)
{
int n=size;
int max=arr[0];
for (int i=1;i<n;i++) {
if (arr[i]>max) {
max=arr[i];
}
}
int *output_array=new int[n];
for (int i=0;i<n;i++) {
output_array[i]=0;
}
int *count=new int[max+1];
for (int i=0;i<=max+1;i++) {
count[i]=0;
}
for (int i=0;i<n;i++){
count[arr[i]]=count[arr[i]]+1;
}
for (int i=1;i<max+1;i++) {
count[i]=count[i]+count[i-1];
}
for (int i=n-1;i>=1;i--) {
output_array[count[arr[i]]-1]=arr[i];
count[arr[i]]=count[arr[i]]-1;
}
cout<<"The sorted elements are:"<<endl<<endl;
for (int i=0;i<n;i++) {
cout<<output_array[i]<<" ";
}
cout<<"\n-----------------------------------------------"<<endl;
return 0;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
clock_t t1,t2;
t1=clock();
sort s1;
s1.read_file();
t2 = clock();
float diff = ((float)t2 - (float)t1)/1000 ;
cout <<"The time taken to execute this process is:\n"<< diff<<" Milliseconds." << endl;
return 0;
}
int *count=new int[max+1];
for (int i = 0; i <= max+1;i++) {
count[i]=0;
}
Note that here you goes out of range, because you try to access the last element as count[max+1], because the <= in the conditional test, and this position is not allocated. It should be like this:
int *count=new int[max+1];
for (int i = 0; i < max+1;i++) {
count[i]=0;
}
I suggest to you to carefully check each for, looking if you aren't accessing some position not bounded/allocated. Use printf's or cout's to debug, this is really useful.
I am having a run-time error in this program, it has no syntax error but crashes when it is run. i am using dev-c++ 4.9.9.2. I tried to find the error but i couldn't find it. If anyone can help then please find the errors and correct me.
#include<iostream.h>
void DisplayVUID();
void DisplayReverse(char[], int);
void StoreDiagonal();
main()
{
DisplayVUID();
char a[20] = "mc123456789";
DisplayReverse(a, 20 );
StoreDiagonal();
system("pause");
}
void DisplayVUID()
{
int i;
char name[20] = "mc123456789";
cout<<"My VU id is ";
for(i=0;i<20;i++)
{
cout<<name[i];
}
cout<<endl;
}
void DisplayReverse(char a[], int arraysize)
{
int i;
cout<<"MY VU id in Reverse is ";
for(i=arraysize-1;i>=0;i--)
{
cout<<a[i];
}
cout<<endl;
}
void StoreDiagonal()
{
int a[9][9] ;
int i;
int row, col;
for (i = 0; i<9;i++)
{
for(i=0;i<9;i++)
{
a[row][col] = 0;
}
}
a[1][1] = 1;
a[2][2] = 3;
a[3][3] = 0;
a[4][4] = 2;
a[5][5] = 0;
a[6][6] = 2;
a[7][7] = 3;
a[8][8] = 9;
a[9][9] = 8;
for(i = 0 ; i < 9 ; i ++)
{
for( i = 0 ; i < 9 ; i ++)
{
cout<<a[row][col];
}
}
}
Things don't work this way on Stackoverflow, from next time onward try hard to do things on your own, do your research and then come here.There seemed to be many errors in your program but I tried to remove some bugs and finally, It works on my system. I have also recommended some nice things via comments that you can look in the program:
EDIT: I noticed that some undefined string because of unassigned spaces in the array was printed out in the reverse function but i have corrected it now.
#include<iostream>
#include<stdlib.h>
using namespace std;// use namespace otherwise cout won't work
void DisplayVUID();
void DisplayReverse(char[], int);
void StoreDiagonal();
int main()// In C++ always declare a main function like this,its good habit
{
int i=0;
DisplayVUID();
char a[20] = "mc123456789";
while(a[i]!='\0')
i++;// Did this to ensure that cout will print only up to the null character,earlier it was printing some undefined characters along with the data in the array.
DisplayReverse(a, i );
StoreDiagonal();
system("pause");
return 0;//return 0
}
void DisplayVUID()
{
//int i;
char name[20] = "mc123456789";
cout<<"My VU id is ";
//for(i=0;i<20;i++)// no need for this loop at least here
//{
cout<<name;
//}
cout<<endl;
}
void DisplayReverse(char a[], int i)
{
cout<<"MY VU id in Reverse is ";
// for(i=arraysize-1;i>=0;i--)
//{
while(i--)
cout<<a[i];//instead of the for loop traversing for the whole arraysize i have made it go up to only the null terminator this way it doesn't print undefined characters.
//}
cout<<endl;
}
void StoreDiagonal()// i don't understand by the way what this function is here for , its not an error though.
{
int a[9][9] ;
int i,j,c=1;
//int row, col;// you didn't initialize row and column and placed it inside the loop
for (i = 0; i<9;i++)
{
for(j=0;j<9;j++)
{
a[i][j] = 0;
if(i==j)
{
a[i][j]=c;//instead of manually assigning do it like this.
c++;
}
}
}
for(i = 0 ; i < 9 ; i ++)
{
for( j = 0 ; j < 9 ; j ++)
{
cout<<a[i][j];// the elements of the array don't display like a table , this is not an error but to make your output readable do it by your self
}
}
}
a[9][9]=8;
remove this line, you will be fine. Array indexing starts from 0 not 1.
Also I would like to point that in your function DisplayVUID() change i<20 to a[i]!='\0' because the values after '\0' will be garbage values.
I have a bit of a problem, I am writing a program to ask the user to enter numbers for a Sudoku grid, and then store them in a 2-d array. I know how to print out the array to show the Sudoku grid, But I am having trouble getting the array elements set to the numbers that the user enters, can anyone help?
This is all that I have, which I know is not much but I have only ever done this with 1-d arrays before.
Code:
#include <iostream>
using namespace std;
void fillGrid1(int grid1, int sizeOfArray) {
for(int x = 0; x < sizeOfArray; x++) {
grid1[x][9] = x;
}
}
int main()
{
int grid1[9][9];
fillGrid1(grid1, 9);
for(int row = 0; row < 9; row++) {
for(int column = 0; column < 9; column++) {
cout << grid1[row][column] << " ";
}
cout << endl;
}
}
Here you have two functions, one to interactively fill the hole sudoku by getting the user input. The other for printing the sudoku. With the little information you gave it's what I think you seek:
#include <iostream>
#include <stdio.h>
#include<stdlib.h>
using namespace std;
void interactiveSudokuFill(int grid1[9][9]){
for(int y=0;y<9;y++){
for(int x=0;x<9;x++){
string theString;
cout<<"Write the value to prace in Sudoku["<<y<<"]["<<x<<"] :"<<endl;
std::getline(cin,theString);
int nr=atoi(theString.c_str());
grid1[y][x]=nr;
}
}
}
void printSudoku(int grid[9][9]){
for(int y=0;y<9;y++){
for(int x=0;x<9;x++){
cout<<"["<<grid[y][x]<<"]";
}
cout<<endl;
}
}
int main()
{
int grid1[9][9];
interactiveSudokuFill(grid1);
printSudoku(grid1);
}
There are other more safe/elegant ways of doing this(for example user input should have been checked before delievering it to atoi()), but this way is the simpler I can think of.
Firstly, you're taking in an int where you expect an array:
void fillGrid1(int grid1, int sizeOfArray)
// ^^^^^^^^^
This should be something of the form,
void fillGrid1(int grid1[9][9], int sizeOfArray)
Next is that you should use a nested loop to access the elements of the multidimensional array:
void fillGrid1(int grid1[9][9], int sizeOfArray)
{
for (int i = 0; i < sizeOfArray; ++i)
{
for (int k = 0; k < sizeOfArray; ++k)
{
grid1[i][k] = x; // shouldn't x be the number the user entered?
}
}
}
You should also zero-fill your array:
int grid1[9][9] = {0};
I am getting a crash error at run time and not sure what exactly to do with the function or how to get the data for it.
FUNCTION DETAILS
Write a function that accepts an int array and size as arguments, then create a new array that is one element bigger than the given. Setting the first element to 0, then copying over what is in the argument array to the new array.
MAIN DETAILS
Use in a program reading int n from input, then read int n from file data name data
passing it to element shifter, then printing it to output (one per line).
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int element_shift(int elmts[], int size) {
int new_size = size + 1;
int shifter[new_size];
int *elmt_sft;
shifter[0] = 0;
for (int i = 1; i >= new_size; i++) {
shifter[i + 1] = elmts[i];
}
return *elmt_sft;
}
int main() {
fstream infile;
infile.open("D:\\data.txt");
int n, x;
infile >> x;
cout << "size of array: ";
cin >> n;
const int ARRAY_SIZE = n + x;
int elements[ARRAY_SIZE];
element_shift(elements, ARRAY_SIZE);
system("PAUSE");
return EXIT_SUCCESS;
}
First of all ARRAY_SIZE declared in the main function is not a constant variable but defined at run-time depending on user inputs. This means that the array elements should be created dynamically. On the other hand you read some x variable which is only used to define the size of the array and didn't initialized the array at all. I guess that the problem statement is to read the size of the array from the input, then the data of the array from the file.
There are also lot of mistakes in element_shift function.
Your code should look like something similar to this:
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
void element_shift(int* elmts, int size)
{
int new_size = size + 1;
int* shifter = new int[new_size];
shifter[0] = 0;
for(int i = 0; i < size; ++i)
{
shifter[i + 1] = elmts[i];
}
delete [] elmts;
elmts = shifter;
}
int main()
{
fstream infile;
infile.open("D:\\data.txt");
int n;
cout << "size of array: ";
cin >> n;
int* elements = new int[n];
for (int i = 0; i < n; ++i) {
infile >> elements[i];
}
element_shift(elements, n);
for (int i = 0; i < n; ++i) {
std::cout << elements[i] << std::endl;
}
return EXIT_SUCCESS;
}
First off, you spend alot of time creating the shifted array but don't return it back.
int element_shift(int elmts[], int size) {
int new_size = size + 1;
int shifter[new_size];
int *elmt_sft;
shifter[0] = 0;
for (int i = 1; i >= new_size; i++) {
shifter[i + 1] = elmts[i];
}
return *elmt_sft;
}
The elmt_sft pointer is never assigned. You are trying to access memory that is not there by using *elmt_sft. This may be causing your error. Also this function has no way of returning the new array shifter because that variable is locally declared and will disappear once the function exits. If you want to create something new in the function and still have it in memory once the function exits, I recommend creating the array dynamically and returning a pointer to it.
This is untested but should start you in the right direction. It will return a separate dynamically allocated array that will not override your other one.
int* element_shift(int elmts[], int size) {
int *result_array = new int[size + 1]; //dynamically create new array MAKE SURE TO DELETE
result_array[0] = 0; //set 0 index to 0
for (int i = 1; i < size + 1; i++)//start at 1 of the result and put value in
{
result_array[i] = elmts[i - 1];
}
return result_array; //returning pointer
}