home_wrecker
home_wrecker

Reputation: 375

make strings out of chars from argv[1] at runtime

Learning some C syntax here, and I've run into something that I find a bit confusing. I am trying to make two functions:

1) char* extractCharacters(char** input) Take argv[1] from main and extract the first two characters (they can be any readable ascii characters)make a string out of them. Return that string.

2) char* concatenate(char* string1, char* string2) Take the string returned from function 1 above, and concatenate it with a second input string supplied by main.

For this one, I have:

char* concatenate(char* string1, char* string2)
{
char* concatenated = malloc(strlen(string1)+strlen(string2)+1);
strcpy(concatenated, string1);
strcat(concatenated, string2}
return concatenated
}

When it comes to function 1, I understand argv is a the pointer of a pointer, I just dont really get how to go from that to a string at runtime. Sorry if the question is a bit noobish.

Thanks!

Upvotes: 0

Views: 164

Answers (2)

AngeloDM
AngeloDM

Reputation: 417

Please, try this solution:

char* concatenate(char* string1, char* string2)
{
    char* concatenated = (char*)malloc(strlen(string1)+strlen(string2)+1);
    sprintf(concatenated, "%s%s", string1, string2);
    return concatenated;
}

int main(char* argv[], int argc )
{
   char string1[100];
   char* string2 = "stice";
   strncpy(string1, argv[1], 2);
   char* string3 = concatenate( string1, string2);

}

Upvotes: 0

this
this

Reputation: 5290

argv points to an array of character pointers. Each character pointer points to a c string.

char* third_string = argv[2] ;

char second_char_of_third_string = argv[2][1] ;

extractCharacters() should be take a character pointer instead, just like concatenate().

Upvotes: 1

Related Questions