This question already has answers here:
Passing a 2D array to a C++ function
(18 answers)
Closed 9 years ago.
I wrote a little programm and I can't pass two-dimensional array words[10][max_row_size] to function notify. Please help me if you can. a part of code attached.
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string.h>
#include <unistd.h>
using namespace std;
#define max_row_size 100
int notify(char words[max_row_size]);
int main(void) {
ifstream dictionary("dictionary.txt");
//ditrionary looks like
//hello-world
//universe-infinity
//filename-clock
string s;
int i=0;
char words[10][max_row_size];
while(!dictionary.eof()){
dictionary>>s;
strcpy(words[i++],s.c_str());
}
notify(words[max_row_size]);
return 0;
}
int notify(char words[max_row_size]){
cout<<words[1];
return 0;
}
It is a full code of my programm, may be it can help you
It is an errors
/home/rem/projects/github/notify_words/notify_words.cpp: В функции «int notify(int, char*)»:
/home/rem/projects/github/notify_words/notify_words.cpp:65:113: предупреждение: format «%s» expects argument of type «char*», but argument 3 has type «int» [-Wformat]
You pass words on its own: char** words is the argument in the function: i.e.
int notify(char** words){...
Easiest way for 2 dimensional array (obviously, you can typedef your array):
int notify(std::array<std::array<char, max_row_size>, 10>& words){
std::cout << words[1];
return 0;
}
Easiest for an array of strings:
int notify(std::array<std::array<std::string>, 10>& words){
std::cout << words[1];
return 0;
}
This way prevents that the array is decayed to a pointer in the function, so the size is still known.
notify(char words[][max_row_size])
to pass the whole array down
then use notify(words); to call the method
But really you should be using standard containers instead of arrays
I'm guessing you want notify to print just one word, so you need to change notify to
int notify(char* word){
cout<<word;
return 0;
}
But also the way you're calling notify will probably not produce the results you're after.
notify(words[max_row_size]);
Will try to get you the 100th word out of 10. Which will probably cause a crash.
You probably want to place notify last in your while loop and call it like this
notify(words[i]);
Also, if you have more than 10 words in your dictionary, you're in trouble. You might want to try a vector instead of an array (because vectors can grow dynamically).
Related
This question already has answers here:
How do I find the length of an array?
(30 answers)
Closed 3 years ago.
I was just messing around playing with some code then i suddenly see that after passing a array by reference sizeof(arr)/sizeof(arr[0]) is giving me other output than i expected.If i am just passing the reference then the len=1 may be justified since sizeof(arr[0])/sizeof(arr[0]).What is wrong with this any concept i am missing?
#include<iostream>
using namespace std;
void display(int *arr)
{
int len=sizeof(arr)/sizeof(arr[0]);
cout<<len<<"\n";
for(int i=0;i<50;++i)
{
cout<<arr[i];
}
cout<<"\n";
}
int main()
{
int arr[50]={0};
for(int i=0;i<50;++i)
{
arr[i]=i;
}
display(arr);
return 0;
}
Why is output of lenth not 50 as it should be?Why is it only 2 instead of 50.
Whenever you try to pass an array to any function. The array is implicitly converted to pointer to first element of array. Here in above code as you passed integer array it get converted to
integer pointer which is pointing an array.
That's why you are getting such result. In array cases you need to pass size explicitly in the function. So sizeof is working fine , it is dividing
size of "pointer to array" with the "size of one element".
Reason behind such casting is that "As you must know that arguments are copied into parameters of the function. But in case of arrays.Array can be of variable size they may be larger size. So it's unnecessary to copy such large array.That's why language implement this casting automatically. "
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:
When a function has a specific-size array parameter, why is it replaced with a pointer?
(3 answers)
Closed 9 years ago.
Why in C++ sizeof(array) behave in different way for bool array then for arrays containing other types of data ?
Edition :
I'm asking because
sizeof(boolarray)/sizeof(boolarray[0])
don't give size of boolarray.
but this simple code prints :
4
1
////////////////////////////
#include<iostream>
using namespace std;
void printBoolArray(bool* boolarray){
cout<<sizeof(boolarray)<<"\n";
cout<<sizeof(boolarray[0]);
}
int main(){
bool boolarray[10]={false};
printBoolArray(boolarray);
}
know I understand sizeof in function which gives the size of object which makes reference, this is my 9 day with c++, sorry for stupid question, it's so obvious now
It doesn't act differently. What makes you think it does? Are you making incorrect assumptions about the size of a bool?
As has been alluded to in the comments, if you are passing an array to a function and attempting to calculate its size there, that doesn't work. You can't pass arrays to (or return them from) functions. For example:
void foo(int array[10])
{
auto size = sizeof(array);
// size == sizeof(int*), you didn't pass an array
}
#include <cstddef>
#include <iostream>
template<std::size_t n>
void printBoolArray(bool (&boolarray)[n]){
std::cout<<sizeof(boolarray)<<"\n";
std::cout<<sizeof(boolarray[0]);
}
int main(){
bool boolarray[10]={false};
printBoolArray(boolarray);
}
The above works.
sizeof(bool*) is the size of the pointer, not the array it points to.
Above, I carefully maintained the type of the boolarray. As it happens, this technique also extracts the size into the compile-time constant n.
This doesn't scale well, because when you pass arrays to functions, they rapidly decay to pointers. This is one of the reasons why std::array or std::vector can be advised -- they have fewer quirks than C style arrays.
As others have explained, arrays degenerate to pointers when passed to a function.
However, there is one work around; you can use templates.
template<typename T, size_t N>
size_t length(T (&)[N]) {
return N;
}
I am wondering is it okay to return a vector in main()? For example,
aSpecialVectorType main()
{
aSpecialVectorType xxx(vector::zero);
// do something here;
return xxx;
}
Do I need to forward declare "class aSpecialVectorType;" before main()?
And btw, is it legal to use another name other than "main" in c++?
Thanks
Edit1:
If not, what is the best way that it can output a vector?
My friend ask me to give him a blackbox that can serve as "vector in and vector out", he will use his matlab code to call my code. That's why I am asking.
I know how to vector in, but not sure if there is an easy way to output a vector.
Thanks
Edit2:
I am surprised why C++ has such an standard, any explanation? :)
In C++, main needs to return an int:
C++ standard, 3.6.1.2:
An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined.
.
If not, what is the best way that it can output a vector?
To output a vector, you need to copy it to a file or an output stream:
ostream_iterator<int> out_it(cout, ", ");
copy(myvector.begin(), myvector.end(), out_it);
The code fragment above writes the content of vector<int> to the standard output.
No. main must be declared in one of these two ways:
int main()
or
int main(int argc, char*[] argv)
Anything outside of this is not standard.
No.
According to the standard main() must return an int and only that.
No.
main must return int.
Other functions are free to have other names and return anything they want.
To expand on dashblinkenlight's answer, here is how two programs can communicate. Not by one capturing the return value of the other, but by a process called "piping", directing the standard output of one program to the standard input of another. Here, I'll print out a list of strings in one program, then the other program will expect a list of strings on its standard input, then I'll show you how to use the two together:
// Output program
#include <vector>
#include <string>
#include <iostream>
int main()
{
using namespace std;
vector<string> v;
v.push_back("one");
v.push_back("two");
v.push_back("three");
for (int i=0; i<v.size(); ++i)
cout << v[i] << '\n';
}
// input program
#include <iostream>
#include <vector>
#include <string>
int main()
{
using namespace std;
vector<string> v;
for (string tmp; cin >> tmp; )
v.push_back(tmp);
// print the strings in reverse order
for (int i=v.size()-1; i>=0; --i)
cout << v[i] << '\n';
}
If you run the first program by itself, it will just print the 3 strings out. If you run the second program by itself, it will prompt the user for strings until he uses the termination command. But on all of the most widely used operating systems, you can chain the two together. Then the output of the first will become the input of the second. On Unix-like systems, you do it like this:
./output_program | ./input_program
On Windows, I think it's the same, or very similar. Not sure though.
The answer to your first question is no.
The answer to your second question is yes, but you need to specify the name of your entry point to your executable (via linker settings ... may not be available on all linker tools).
Below statement is wrong
See Ben's comment below. Useful info that.
Be aware that though the name of the entry-point can change, it MUST conform to the standard parameter and return types.
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?