I have given the array size manually as below:
int main(int argc, char *argv[] )
{
char buffer[1024];
strcpy(buffer,argv[1]);
...
}
But if the data passed in the argument exceeds this size, it may will create problems.
Is this the correct way to allocate memory dynamically?
int main(int argc, char *argv[] )
{
int length;
char *buffer;
length = sizeof(argv[1]); //or strlen(argv[1])?
buffer = (char*)malloc(length*sizeof(char *));
...
}
malloc()is generally misguided (and rawchar *is also not a good idea). If you're working in C, you don't need the C++ tag. In fact, don't dual-tag the question — they are two distinct languages.sizeof()orstrlen()", usingstrlen(argv[1])+1will work as you want it to (and usingsizeofwill generally not allocate enough memory). Bigger question, why do you need a copy of the data thatargv[1]points at?