Pelles C forum

C language => Beginner questions => Topic started by: andre104 on June 19, 2008, 03:58:34 PM

Title: Why *argv[], and not argv[] ?
Post by: andre104 on June 19, 2008, 03:58:34 PM
Sometimes I take things for granted  ;D
E.g when you write command line apps, you will do this :
Code: [Select]
int main(int argc,char *argv[]){
}

How different would it be, if instead of that,I do this:
Code: [Select]
int main(int argc,char argv[]){
}
Title: Re: Why *argv[], and not argv[] ?
Post by: DMac on June 19, 2008, 05:54:07 PM
You wouldn't be able to accept switches.

Typical switch: "\x \y" is passed to the application.

if argv[] then the character array would look like this
Code: [Select]
[0] = '\'
[1] = 'x'
[2] = [NULL]
[3] = ' '
[4] = '\'
[5] = 'y'
[6] = [NULL]
if *argv[] then the pointer array points to the location of each null terminated character array (string) separated by a space and looks like this
Code: [Select]
[0] = "\x"
[1] = "\y"
Title: Re: Why *argv[], and not argv[] ?
Post by: PauloH on June 20, 2008, 02:31:09 AM
Hi,

Andre104, in the first case you have an array of pointers to char (in other words each array member points to a character sequence) . Each pointer in this array points to an argument received from command line when you execute the program like this:
Code: [Select]
program.exe arg1 arg2 arg3 ...

Each arg is a complete string that corresponds to an element into *argv[] array.

In the second case you have a array of char. The interpretation is like Dmac explained above, where each position of this array is a character only and not a complete string.

Paulo H.

PS: (Where are you from? Are you from Brazil?)
Title: Re: Why *argv[], and not argv[] ?
Post by: frankie on June 23, 2008, 10:51:03 AM
What Dmac and PauloH said is correct when it's you that define the variable type. But the problem you will experience making the wrong declaration is that you will access as a char string an array of binary addresses. This is because when main is invoked the parameter passed is an array of addresses that points to a zero terminated string each, so when you will access them as char you'll get meaningless series of strange chars. In the worst case if none of the addresses in the array contains a byte with value zero you will scan the memory looking for string closing char up to a memory violation.