c - Segmentation Fault (core dumped) printing string from argv -


i'm trying check commandline arguments , see if works in command line. works fine if execute './a.out hello' when './a.out' error.

#include <stdio.h>  int main(int argc, char * argv[]){    printf("test");    printf("\n%s",argv[0]);    printf("\n%s",argv[1]); return 0; } 

the reason why i'm doing because i'm going take string , compare later on. don't understand why simple causing error.

you're not checking length of argv before dereferencing second argument. if argv has 1 element argv[1] null reference, causes fault.

with c everything needs done carefully. answer question, yes, if statement right approach if want handle command line yourself. argc parameter main() provided purpose.

#include <stdio.h>  int main(int argc, char * argv[]){   printf("test");   if (argc > 0) {       printf("\n%s", argv[0]);       if (argc > 1) {           printf("\n%s", argv[1]);       }   } return 0;  } 

theoretically argv[0] populated application name first if redundant c caution friend.

however, don't take path. except trivial applications should use parameter parsing library such http://www.gnu.org/software/libc/manual/html_node/getopt.html, check christian's excellent answer here https://stackoverflow.com/a/24479532/2381157 more options.


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -