Click to See Complete Forum and Search --> : [RESOLVED] argv[] parameter question


pouncer
August 22nd, 2006, 09:44 AM
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

NMTop40
August 22nd, 2006, 09:49 AM
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

char test [] = "Hello there how is everyone"

and you should find the program works.

pouncer
August 22nd, 2006, 01:05 PM
thanks that fixed the problem

compiler im using is ms vs 6.0

pouncer
August 22nd, 2006, 01:18 PM
another problem guys, sorry,


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

Paul McKenzie
August 22nd, 2006, 04:55 PM
another problem guys, sorry,


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' :SSimple 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

exterminator
August 23rd, 2006, 06:29 AM
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.