This question already has answers here:
C++ : Creating an array with a size entered by the user
(3 answers)
Closed 3 years ago.
I am trying to get a user input and set it as the PUZZLESIZE which is used by int peg and row but am getting the expression must have a constant value.
How would I go about getting a user input and setting it as a global const that struct Board will recognize?
int a;
const int PIECE = a;
const int PUZZLESIZE = ((PUZZLESIZE *(PUZZLESIZE+1)) /2);
typedef struct Board {
int *row[PUZZLESIZE];
int peg[PIECE];
int lastmove;
struct Board *prevBoard;
int prow;
int pcol;
} Board;
int main()
{
scanf("%d",a);
}
Thanks for any help in advanced
Re-setting the value of a const variable at runtime is not possible.
You just defined PIECE as a const (constant variable):
const int PIECE = a;
So, you cannot change the value of PIECE after starting the program.
You have to rethink a little about how your program will work. In addition since you are using C++ you may consider the use of the language features and libraries so that you can follow best practices as recommended by #Joren.
You have 2 options:
Option 1 : Make PuzzleSize your largest supported puzzle.
If you do this all you need to do is validate the user input against this size.
In addition you don't have to fiddle with memory allocation.
Simple solution
Potentially can have large segments of unused memory
Option 2: Make row a double pointer and use new to allocate your rows.
typedef struct Board
{
int **row; // int *row[PUZZLESIZE];
....
}
once the user sets the input you can validate the input and do this
int main()
{
scanf("%d",a);
row = new int*[a]; }
Don't forget to take a look at your C++ book and read up on const, multidimensional arrays ,and new.
Good Luck!
Related
This question already has answers here:
Why does Sizeof operator on a std::string yield unexpected result? [duplicate]
(3 answers)
Why is sizeof(std::string) only eight bytes?
(2 answers)
What is the proper size of std::string in C++? [duplicate]
(2 answers)
Closed 1 year ago.
I've been handed legacy code that I need to insert a new feature into... For the feature I am populating the message struct that was provided to me and then pack it into a vector. However I am running into issues where the data isn't making it all the way over in one piece. I know that my struct is causing the issue since when I so a sizeof(struct) I get an incorrect size.
struct fault
{
std::string n, d;
bool rec;
int sev;
std::vector diagData;
}
void MsgPack::pack(std::string n, std::string d, bool r, int s)
{
fault Msg;
fault.n = n;
fault.d = d;
fault.rec = r;
fault.sev = s;
std::size_t size = sizeof(fault); //ALWAYS returns 48 no matter how large strings are.
unsigned char* data;
memcpy(data, (const unsigned char*)&fault,size);
std::vector<char> p;
for(int i=0;i<size; i++)
{
p.push_back(data[i]);
}
sendMsg(p);
}
So I know there are several problems with this code, from the push_back, to the always returning 48... My questions are as follows:
I know that I can define the struct to contain chars that are predefined in size; however, the API call that I'm trying to make takes a string as an argument. I want to allow for the user to write anything that need/want and not box them in. Is there a way to keep the strings in the struct?
Is there a better way to do the push_back? I know that it iterating over 48 8byte chunks will either put too much or too little into the vector.
Just general coding practices and advice... Its been about 5yrs since I coded last so I am very rusty. I usually don't touch code so please go gentle on me :).
This question already has an answer here:
Can we create variable length arrays in c++
(1 answer)
Closed 2 years ago.
int a;
cin>>a;
int arr[a];
I want to declare an array according to size of the user. I am new to programming .
What can be done? Is this method correct?
The thing you want to achieve is called Variable Length Array, in short VLA which isn't a part of C++ standard.
What can be done?
It invokes an undefined behavior.
Is this method correct?
Nope. The best opportunity of taking a little help of std::vector<> worth here. It dynamically allocates the requested bytes of data and optionally, you can initialize them with their required values.
You can achieve this like:
int n = 0;
std::cin >> n; // make sure it's a valid size
std::vector<int> a(n);
In case you wants it to keep growing runtime, just use its push_back() method and you can get the vector size through its size().
You've tagged this C++, in which case there are very few excuses not to solve this with a std::vector.
If you must do it C style you can write:
int a;
cin >> a;
int * arr = (int *)malloc(sizeof(int) * a);
or better (as per Thomas' comment below):
int a;
cin >> a;
int * arr = new int[a];
but a vector is definitely preferred.
I have been given following assignment
Write a simple telephone directory program; contain two dimensional arrays in which you have hard code names and telephone number. Then declare a simple character array. You have to prompt user to enter any name, which you want to search. This name should be store in this character array, then search this name from the two dimensional array. If number is found against entered name then program should display the number against this name, and if not found then program should display the message that name is not registered.
Here is my code but i could not get the number when i search for the name. I am new to coding so i am having trouble making this code work. Help is appreciated.
#include <iostream>
#include <conio.h>
using namespace std;
int getPhone(int p[5][10],int row, int col, char key[10],char n[5][10]);
int main() {
int i,j;
char search[10];
const int r = 5;
const int c = 10;
int element;
int phone[r][c] =
{
42-5429874,
42-5333156,
42-9824617,
42-9927562,
42-6238175
};
char name[r][c] = {"shazia","zara","sana","ahmad","maha"};
cout<<"\nEnter name to find in directory : ";
cin>>search[r];
element = getPhone(phone,r,c,search,name);
cin.get();
return 0;
}
int getPhone(int p[5][10],int row,int col,char key[10], char n[5][10]) {
int i, j;
for(i=0;i<row;i++)
for(j=0;j<col;j++)
p[5][10] = p[i][j];
if(key[j] = n[5][10])
cout<<"The desired number is: "<<p[i][j]<<endl;
else if(key[j]!=n[5][10])
cout<<"Sorry! This name is not registered.";
return p[i][j];
}
Your code contains several mistakes. Let's examine them.
for(i=0;i<row;i++)
for(j=0;j<col;j++)
p[5][10] = p[i][j];
Here, you make no change on your array, because just the value of p[5][10] is changed. Furthermore, you access an invalid memory zone, because array indexes go from 0 to size - 1 in C++. So last index is p[4][9].
if(key[j] = n[5][10])
In C++, comparing two values needs two =, because only one is an affectation that results the if to be always true. A tip to remember: two values to compare need two =.
else if(key[j]!=n[5][10])
The same than before, you access invalid memory zone. And are you sure that j is valid, e.g less than 10 ? If not, you do double invalid access.
cin>>search[r];
As search is an array of char, you do an input of only a single char there, which I think is not what you want and that can leads to segfault.
int phone[r][c] =
{
42-5429874,
42-5333156,
42-9824617,
42-9927562,
42-6238175
};
Your array is not good, a simple 1-dimension array is enough, not 2-dimensions. Furthermore, 42-54.. does a subtraction, and I think is not what you want.
There are others mistakes. But why not using C++ abstractions, like std::vector, or std::string? Your life would get so much easier. But I guess you have an old teacher that never took time to learn C++ news, or that is not a good teacher.
As a beginner, I suggest you to read C++ Primer and Programming: Principles and Practice Using C++ to introduce you both programming and modern C++.
I've Googled, asked my classmates, and finally asked my professor about this particular problem, but I haven't achieved a solution yet. I'm hoping someone here can help me out.
Basically, I need to make an array of structs that will contain 4 pieces of information per struct: country name, country population, country area, and country density. This information will be written to the structs in the array from a .txt document. This info will then be written onto the console from said array.
Unfortunately, in attempting to write anything to the structs in the array, I get 2 errors. "Cannot convert from 'const char[8]' to 'char [30]'" and "no operator '[]' matches these operands, operand types are: CountryStats [int]". These errors both refer to the line:
countries[0].countryName = "A";
Keep in mind that I have only started to use structs and this is the first time I've used them in an array. Also, I must use an array, as opposed to a vector.
Here's my code:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
struct CountryStats;
void initArray(CountryStats *countries);
const int MAXRECORDS = 100;
const int MAXNAMELENGTH = 30;
struct CountryStats
{
char countryName[MAXNAMELENGTH];
int population;
int area;
double density;
};
// All code beneath this line has been giving me trouble. I need to easily edit the
// struct variables and then read them.
int main(void)
{
CountryStats countries[MAXRECORDS];
initArray(*countries);
}
void initArray(CountryStats countries)
{
countries[0].countryName = "A";
}
As of now I am just attempting to figure out how to write information to a struct within the array and then read the information off of it onto the console. Everything else should fall into place after I find the solution to this.
Oh, and one final note: I have not quite learned the function of pointers (*) yet. I am still relatively new to C++ as my past programming education has been primarily in Java. Any and all inclusions of pointers in this code have been influenced by my classmates and professor in the pursuit of solving this problem.
Thanks in advance!
Two problems
void initArray(CountryStats countries)
must be:
void initArray(CountryStats *countries)
And you must use strcpy to copy c style string. (but i suggest to use c++ string instead of char[])
strcpy(countries[0].countryName,"A");
But I say again, use c++ features like vector<> and string.
You are not defining a definition for:
void initArray(CountryStats *countries);
but for:
void initArray(CountryStats countries);
in which countries is not an array. Since no operator[] is defined for CountryStats, the expression countries[0] fails to compile.
Since you cannot use std::vector (for some weird reasons), I'd suggest you to use an std::array:
template<std::size_t N>
void initArray(std::array<CountryStats, N>& ref) {
for (std::size_t i = 0; i < N; i++)
// initialize ref[i]
}
Of course, if you feel masochist, you can also use a C-style array:
void initArray(CountryStats* arr, int size) {
for (int i = 0; i < size; i++)
// initialize arr[i]
}
But you'll, probably, need to provide the dimension of the array as a second parameter.
This question already has answers here:
Why can one specify the size of an array in a function parameter?
(3 answers)
Closed 3 years ago.
This feels like a really stupid thing to ask, but I had someone taking a programming class ask me for some help on an assignment and I see this in their code (no comments on the Hungarian notation please):
void read_dictionary( string ar_dictionary[25], int & dictionary_size ) {...
Which, as mainly a C# programmer (I learned about C and C++ in college) I didn't even know you could do. I was always told, and have read since that you're supposed to have
void read_dictionary( string ar_dictionary[], int ar_dictionary_size, int & dictionary_size ) {...
I'm told that the professor gave them this and that it works, so what does declaring a fixed size array like that even mean? C++ has no native way of knowing the size of an array being passed to it (even if I think that might've been changed in the newest spec)
In a one dimensional array It has no significance and is ignored by the compiler. In a two or more dimensional array It can be useful and is used by the function as a way to determine the row length of the matrix(or multi dimensional array). for example :
int 2dArr(int arr[][10]){
return arr[1][2];
}
this function would know the address of arr[1][2] according to the specified length, and also the compiler should not accept different sizes of arrays for this function -
int arr[30][30];
2dArr(arr);
is not allowed and would be a compiler error(g++) :
error: cannot convert int (*)[30] to int (*)[10]
The 25 in the parameter declaration is ignored by the compiler. It's the same as if you'd written string ar_dictionary[]. This is because a parameter declaration of array type is implicitly adjusted to a pointer to the element's type.
So the following three function declarations are equivalent:
void read_dictionary(string ar_dictionary[25], int& dictionary_size)
void read_dictionary(string ar_dictionary[], int& dictionary_size)
void read_dictionary(string *ar_dictionary, int& dictionary_size)
Even in the case of the first function, with the size of the array explicitly declared, sizeof(ar_dictionary) will return the same value as sizeof(void*).
See this sample on Codepad:
#include <string>
#include <iostream>
using namespace std;
void read_dictionary(string ar_dictionary[25], int& dictionary_size)
{
cout << sizeof(ar_dictionary) << endl;
cout << sizeof(void*) << endl;
}
int main()
{
string test[25];
int dictionary_size = 25;
read_dictionary(test, dictionary_size);
return 0;
}
Output (the exact value is, of course, implementation-dependent; this is purely for example purposes):
4
4
I always though that passing fixed size C++ arrays was a "half baked" feature of C++. For example, ignored size matching or only being able to specify the first index size, etc... Until recently I learn this idiom:
template<size_t N1, size_t N2> // enable_if magic can be added as well
function(double(&m)[N1][N2]){
... do something with array m...knowing its size!
}
Reference: Can someone explain this template code that gives me the size of an array?