Concatenation of two char array C -


int main(int argc, char *argv[]) {   char *s = argv[1];   *(s + (strlen(argv[1]))) = argv[2];   printf("%s \n", s);   return 0; } 

when run: ./concat hello, world output is:
hello,mworld while expect
hello,world

what m char? , why c put this?

you not appending here:

   *(s+(strlen(argv[1])))=argv[2]; 

you assigning char* null byte of of argv[1] i.e. it's equivalent to

 argv[0][strlen(argv[1])] = argv[2]; 

this wrong , turn compiler warnings proper diagnostics. in general, concatenate strings, need use strcat or snprintf.

in specific case, can't use strcat or snprint arguments main() not have additional memory append. need use auxiliary array or `malloc'ed pointer concatenation.

you should check if there enough arguments passed main() before attempting use them.

note that, can modify argv[x]. example, if execute as:

./a.out stack overflow 

then can do:

argv[1][1] = 'l';  //argv[1] "slack" 

and on, long don't go beyond boundary. can treat pointer array can modify.

c11, 5.1.2.2.1 program startup, p2 states

the parameters argc , argv , strings pointed argv array shall modifiable program, , retain last-stored values between program startup , program termination.

(emphasis mine)


Comments

Popular posts from this blog

android - Pass an Serializable object in AIDL -

How to provide Authorization & Authentication using Asp.net, C#? -

How to use Authorization & Authentication in Asp.net, C#? -