To solve my problem here, I want to know if/how I can define the second variable of the command line arguments in a format other than char** argv
or char* argv[]
. The reason is that pybind11 doesn't allow either of those in the inputs of a function. Here are the methods I have tried:
Method 1:
#include <stdio.h>
int main(int argc, int* argv_){
for (int i = 0; i < argc; ++i){
printf("%s\n", (char *)(argv_[i]));
}
}
The rationale behind this method is that a pointer is intrinsically an integer and by casting the address to a char
pointer, one should be able to get the strings. Thanks for your kind support in advance.
Method 2:
#include <stdio.h>
#include <string>
int main(int argc, std::string* argv_){
for (int i = 0; i < argc; ++i){
printf("%s\n", argv_[i].c_str());
}
}
Method 3:
#include <stdio.h>
#include <string>
#include <vector>
int main(int argc, std::vector<std::string> argv_){
for (int i = 0; i < argc; ++i){
const char* argv__ = argv_[i].c_str();
printf("%s\n", argv_[i].c_str());
}
}
issue:
Unfortunately, all of the above methods lead to the infamous segmentation fault
.
I would appreciate it if you could help me know what is the problem (i.e., where is the memory leak) and how to solve them.
workaround/hack:
In the comments I'm being told that if any other form rather than main()
, main(int argc, char** argv)
, or main(int argc, char* argv[])
is used, it will unavoidably lead to segmentation fault
. However, the code below works:
#include <stdio.h>
int main(int argc, long* argv_){
for (int i = 0; i < argc; ++i){
printf("%s\n", (char *)(argv_[i]));
}
}
This works on an Ubuntu minimal and g++ 7.4.0
, and Windows 10 Visual Studio 2019 compilers. However, it does not compile with clang
. As others have pointed out this is not a solution and a very bad practice. It can cause undefined behavior depending on the compiler, operating system and the current state of the memory. This should not be used in any actual code ever. The main function in any C/C++ code must be of the forms main()
, main(int argc, char** argv)
, or main(int argc, char* argv[])
.