[RESOLVED] argv[] parameter question
Code:
int main(int argc, char* argv[])
{
char *test = "Hello there how is everyone";
char * pch;
char * array[10];
int x = 0;
pch = strtok(test, " ");
while (pch)
{
array[x] = pch;
pch = strtok(NULL," ");
x++;
}
Test(array);
return 0;
}
void Test(char * argv[])
{
printf("%s\n", argv[0]); //Hello
printf("%s\n", argv[3]); //is
}
it compiles fine but it just crashes the exe when i run it. says:
text.exe has encountered a problem and needs to close
Re: argv[] parameter question
Compiles fine on which compiler? It should at least generate a warning because you are assigning a literal string to char *. Then you are calling strtok which modifies it - undefined behaviour.
Change the line to
Code:
char test [] = "Hello there how is everyone"
and you should find the program works.
Re: argv[] parameter question
thanks that fixed the problem
compiler im using is ms vs 6.0
Re: [RESOLVED] argv[] parameter question
another problem guys, sorry,
Code:
void Test(char * argv[])
{
printf("%s\n", argv[0]); //Hello
printf("%s\n", argv[3]); //is
printf("%s", argv); //Hello there how is everyone
}
the last printf doesnt print the whole thing, it just prints a 'd' :S
Re: [RESOLVED] argv[] parameter question
Quote:
Originally Posted by pouncer
another problem guys, sorry,
Code:
void Test(char * argv[])
{
printf("%s\n", argv[0]); //Hello
printf("%s\n", argv[3]); //is
printf("%s", argv); //Hello there how is everyone
}
the last printf doesnt print the whole thing, it just prints a 'd' :S
Simple deduction:
1) What is the argv declared as? An array of char pointers.
2) What is the "%s" represent? A null terminated char array.
3) Does "argv" type match what the format specifier "%s" is looking for? No.
An array of char pointers is not a null-terminated array of char. You're lucky the program didn't crash altogether. Give printf() the wrong type that doesn't match the format specifier, the behaviour is undefined.
Look at your previous two lines. Note the difference.
Regards,
Paul McKenzie
Re: [RESOLVED] argv[] parameter question
Change the signature of the Test function from void Test(char * argv[]); to void Test(char * argv[], size_t arraySize); - that will let the code in Test know what the size of argv[] is - similar to what main does. And then you can loop over that many times to show the complete string.