0

I have a code with a character array as follows:

int main (int argc, char** argv)
{
   char arr[] = "%55u%10$n";
   return 0;
}

I wish to dynamically set 10 through a string input from the user, for example argv[1].

What would the correct syntax of the following be:

char arr[] = "%55u%" argv[2] "$n"; // which would basically be "%55u%10$n" if argv[1] == "10"
3
  • That's not the number 10. That's the two characters '1' and '0'. Commented Dec 3, 2019 at 1:44
  • @KenWhite Apologies. Corrected it. Commented Dec 3, 2019 at 1:47
  • You cannot rely on concatenation of string literals with a variable not known until runtime. The compiler has no idea what argv[1] is going to be. See Remy's answer or use strcat Commented Dec 3, 2019 at 1:50

2 Answers 2

2

You can use sprintf():

#include <stdio.h>

int main (int argc, char** argv)
{
   if (argc > 1)
   {
      char arr[20];
      sprintf(arr, "%%55u%%%.12s$n", argv[1]);
      ...
   }
   return 0;
}

Alternatively, use strcpy() and strcat() (use with care!):

#include <string.h>

int main (int argc, char** argv)
{
   if (argc > 1)
   {
      char arr[20];
      strcpy(arr, "%55u%");
      strcat(arr, argv[1]);
      // or: strcat_s(arr, sizeof(arr)-3, argv[1]);
      strcat(arr, "$n");
      ...
   }
   return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Use sprintf. Be sure to escape literal % characters and ensure your buffer is large enough to hold the result string.

#include <stdio.h>
#include <string.h>

int main (int argc, char **argv) {
    if (argc < 2) { return 0; }

    char arr[strlen(argv[1])+8];
    sprintf(arr, "%%55u%%%s$n", argv[1]);
    printf("%s\n", arr);

    return 0;
}

6 Comments

Using a VLA may not be the best option though
Maybe not, but it depends on the use case. Hardcoding 20 might not be the best option, either. Can you elaborate? If a huge input is provided, the stack frame will blow up--would this be a security risk?
I hard-coded 20 in my example because I originally used %d for sprintf(), and the max value for a 32-bit integer is 10 digits. Then I saw the OP's desire to use argv for user input,so I switched my example to %s instead, but 20 is a good limit unless the OP needs more digits
Although OP chose "10", it's not entirely clear that they want to limit input to digits otherwise, and there's nothing preventing the user from providing some non-integer string as it stands.
@ggorlen what about dynamically allocating memory?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.