declaration of ‘args’ as array of references Error [duplicate] - c++

This question already has answers here:
Why are arrays of references illegal?
(14 answers)
Closed 8 years ago.
I am newbie in c++ boost , I having a program trying to compile it

#include "Program.h"
#include <boost/asio/io_service.hpp>
#include <boost/asio/streambuf.hpp>
#include <boost/asio/ip/address.hpp>
#include <boost/asio/ip/udp.hpp>
namespace ConsoleApp
{
void Main(std::wstring& args[])
{
.
.
}
}
the error appear is
Program.cpp:11:31: error: declaration of ‘args’ as array of references
void Main(std::wstring& args[])
anyone here can help me , is this code error ?
thanks

The error is pretty much saying everything. std::wstring& args[] is array ([]) of wstring (std::wstring) references (&). You cannot have array of references - see Why are arrays of references illegal?.
Note: you're coding in C++, main function should be following:
int main(int argc, char *argv[])
{
// Your code
return 0;
}
EDIT:
And AFAIK main function cannot be in any namespace.
Also, there is one more problem with your code - even if we could create array of references, there is not stored information about length of the array. You couldn't use it except first element!
Anyway, you can do following (replaced wstring with string because I'm lazy):
#include <vector>
#include <string>
namespace ConsoleApp
{
void Main(std::vector<std::string> &args)
{
}
}
int main(int argc, char *argv[])
{
std::vector<std::string> args;
args.resize(argc);
for(int i = 0; i < argc; ++i)
{
args[i] = argv[i];
}
ConsoleApp::Main(args);
return 0;
}

Related

Undefined reference to `WinMain' in C++ while exceuting on vectors

I have to calculate the longest prefix string in the program. I am using c++ for this and I don't actually know extensively about vector and its functions.
The code is:
#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
class Solution {
public:
void longestCommonPrefix(vector<string>& strs)
{
string ans;
strs.size(); //no of rows
strs.push_back("flower");
strs.push_back("flower");
string one=strs[0];
string two=strs[1];
int oneL=one.length();
int twoL=two.length();
int min=oneL<twoL?oneL:twoL;
for(int i=0;i<min;i++)
{
char temp=one[i];
if(temp==two[i] )
ans=ans+temp;
}
}
};
This displays an error of winMain and I do understand it must be related to the main function but the problem is I cannot put nain() function here else it displays an error again. Thus, I cannot put a main function and I if I don't I face an error.
Help me out stackmates.

VC++ error C2146: syntax error : missing ')' before identifier 'pFirst'

I am new to C++, but I do pretty well at C# and Java. I am trying to do some basic exercise here:
// HelloWorld.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
bool isSame(int[] pFirst, int[] pSecond, int pLength) {
}
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
That is my entire file, but VC++ (I am using VS 2013) keeps complaining:
1 IntelliSense: expected a ')'
at the isSame declaration line.
What do I do wrong? I am writing a function to compare if two arrays are containing the same values, and here is the solution:
bool ArrayEq( int A1[], int A2[], int size ) {
for (int k=0; k<size; k++) {
if (A1[k] != A2[k]) return false;
}
return true;
}
The correct syntax would be int pFirst[].
But first of all this function already exists in the standard library, and second
std::vector overloads operator ==.
Both should be prefered over handcrafted code and std::vector is better than a C-style array.

simple c++ function inclusion failure

I am trying to include a function from another file inside a "main" file. I'm following this paradigm:
http://www.learncpp.com/cpp-tutorial/18-programs-with-multiple-files/
Here is my main file, digispark.cpp:
#include <iostream>
using namespace std;
int send(int argc, char **argv);
int main()
{
char* on;
*on = '1';
char* off;
*off = '0';
send(1,&on);
return 0;
}
And here is my send.cpp:
#include <stdio.h>
#include <iostream>
#include <string.h>
#if defined WIN
#include <lusb0_usb.h> // this is libusb, see http://libusb.sourceforge.net/
#else
#include <usb.h> // this is libusb, see http://libusb.sourceforge.net/
#endif
// I've simplified the contents of send for my debugging and your aid, but the
// complicated arguments are a part of the function that will eventually need
// to be here.
int send (int argc, char **argv)
{
std::cout << "Hello";
return 0;
}
I'm compiling on Ubuntu 12.10 using the g++ compiler like so:
g++ digispark.cpp send.cpp -o digispark
It compiles successfully.
However, when I run the program, "Hello" does not come up. Therefore I don't believe the function is being called at all. What am I doing wrong? Any help would be great! Thanks!
EDIT:
How I dealt with the issue:
int send(int argc, char **argv);
int main()
{
char* on[4];
on[0] = (char*)"send";
on[1] = (char*)"1";
char* off[4];
off[0] = (char*)"send";
off[1] = (char*)"0";
send(2,on);
return 0;
}
For those of you who were confused as to why I insisted doing this, as I said before, the send function was already built to accept the char** argv (or char* argv[]). My point was to try to mimic that in my main function.
It would have been much more difficult to rewrite the function that actually goes in the send function to take a different type of argument than just to send in what it wanted. Thanks everyone!
So if this helps anyone trying something similar feel free to use it!
Your problem is not the one you think it is. It's here:
char* on;
*on = '1';
You declared a char pointer, but did not initialize it. Then you dereferenced it. Bang, you're dead. This is what is known as Undefined Behavior. Once you invoke U.B., anything can happen. If you're lucky, it's a crash. But I guess you weren't lucky this time.
Look, if you want to start storing things in memory, you have to allocate that memory first. The best way, as hetepeperfan said, is to just use std::string and let that class take care of all the allocating/deallocating for you. But if for some reason you think you have to use C-style strings and pointers, then try this:
char on[128]; //or however much room you think you'll need. Don't know? Maybe you shoulda used std::string ...
*on = '1';
*(on+1) = '\0'; //if you're using C-strings, better null terminate.
char off[128];
*off = '0';
*(off+1) = '\0';
send(1,&on);
ok I think you try to do something like the following, I tried to make it a bit more in the Style of C++ and prevent the use of pointers since they should not be necessary in the code that you showed.
digispark.cpp
#include "send.h"
int main (int argc, char** argv){
string on = "1";
string off = "0";
send ( on );
send ( off );
return 0;
}
send.cpp
#include <iostream>
#include <string>
void send( const std::string& s) {
std::cout << s << std::endl;
}
send.h
void send(const std::string& s);

taking command line input in different ways

How can one take command line argument by not using below structure ?
int main ( int argc, char* argv ) {
}
My question is really : how can I take below input :
./executableProgramName inputX inputY inputZ inputT
in any function ?
in foo () {
// what should I write so that I can get same effect
}
Are there any other way for taking command line input ?
The method specified by the standard for getting command line arguments is the argc and argv parameters passed to the entry point function main. There's no other standard method.
Some platforms offer non-standard methods. For example, if you're on Windows you can use GetCommandLineW
Here's an example that uses some C++11 stuff too.
#include <ShellAPI.h> // for CommandLineToArgvW
#include <string>
#include <vector>
#include <codecvt>
#include <locale>
int main() {
#ifdef WIN32
LPWSTR *szArglist;
int argc;
szArglist = CommandLineToArgvW(GetCommandLineW(),&argc);
if(NULL==szArglist) {
std::cerr << "CommandLineToArgvW failed\n";
}
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t> convert; // codecvt_utf8 or codecvt<char16_t,char,mbstate_t> should work (will work once the char16_t specialization of codecvt works)
vector<string> args;
for(int i=0;i<argc;++i) {
args.push_back(convert.to_bytes(szArglist[i]));
}
#endif //ifdef WIN32
}
Maybe the best way is to forward the handling of command line arguments into an object, or simply a function:
#include <vector>
#include <string>
void handle_commandline_args(const std::vector<std::string>& args){
...
}
int main(int argc, char* argv[]){
handle_commandline_args(std::vector<string>(argv[0], argv[0] + argc));
...
}
You can not arbitrarily get the command-line arguments from any function. In C++, the only way command-line arguments are passed in is through the char* array in the main function.
If you want them to be accessible from anywhere, consider keeping them in a global variable, or passing them into each necessary function call. For example:
int argumentCount;
char **argumentArray;
int main ( int argc, char** argv )
{
argumentCount = argc;
argumentArray = argv;
}
int foo()
{
std::cout << argumentArray[0]; // or whatever
}
If you're working with MSVC++, then you can use below win32 API to get command line arguments anytime in your program:
GetCommandLine
However, this makes your code non-standard. So it is better if you use main(int argc, char *argv[]) to get the command line arguments and save them for later use, e.g to be used by other functions.

C++ command line strings like Java?

Is there a way to get c++ strings from the commandline like in Java?
public static void main(String[] args)
where args is an array of C++ strings?
Not precisely but you can come close easily.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
typedef vector<string> CommandLineStringArgs;
int main(int argc, char *argv[])
{
CommandLineStringArgs cmdlineStringArgs(&argv[0], &argv[0 + argc]);
for (int i = 0; i < cmdlineStringArgs.size(); ++i)
{
cout << cmdlineStringArgs[i] << endl;
}
return 0;
}
This just uses the overloaded constructor for std::vector that takes a begining/ending iterator pair to copy the command line arguments into the vectors. It is much the same as java from there on.
You can likewise build and object around that vector with utility methods to convert arguments but there is almost no point. Also there are plenty of packages with object that deal with interpreting command line switches and such. ACE, POCO, QT, etc.. all come with such facilities.
You can use a vector to get the char array into strings.
#include <vector>
#include <string>
using namespace std;
int main (int argc, char** argv)
{
vector <string> args (argv, argv + argc);
}
Yes the main function can take 2 arguments
int main(int argc, char* argv[])
Where argc is the number of arguments and argv contains a list of the arguments.
For example if you run your program as:
MyProgram.exe hello
Then
argc = 2
argv[0] = MyProgram.exe
argv[1] = "hello"
Not built in to the language, but its very easy to implement:
#include <vector>
#include <string>
using namespace std;
int main( int argc, char *argv[] ) {
vector <string> args;
for ( int i = 0; i < argc; i++ ) {
args.push_back( argv[i] );
}
// do something with args
}
In C, your main function signature looks like this:
int main(int argc, char** argv).
argc contains the number of arguments passed in by the command line. The name of the executable is in position 0, and adds one to argc.
argv contains an array of strings containing the arguments. Again, position 0 is the name of the executable.
The standard C++ main() signature is
int main(int argc, char* argv[])
where argc denotes the count of commandline arguments and argv[] is an array of primitive C strings holding the commandline arguments. argv[0] is the executable, as invoked from the commandline.
If you are writing a win32 application, you can use GetCommandLineW http://msdn.microsoft.com/en-us/library/ms683156(VS.85).aspx and CommandLineToArgW http://msdn.microsoft.com/en-us/library/bb776391(VS.85).aspx
There is a comment on the CommandLineToArg page about special handling that is needed if your executable has spaces in the path and there are no arguments that you might have to handle.