0

How can I pass a variable String, i.e, one that changes during run-time to a function as a parameter?

For example function foo(char * string) takes a string pointer parameter to do something with it. The following loop is uses the above function:

for(int i=0; i<n; i++){
  foo("String"+i);
}

How can I achieve this?

Mostack
  • 35
  • 5
  • What is `+i` trying to accomplish here? – Jason Mar 28 '23 at 13:50
  • @Mostack It is unclear what is the problem and what the function does. – Vlad from Moscow Mar 28 '23 at 13:50
  • What do you think your code doesn't achieve? The only problem I see is that you've declared `foo(char *string)` but you've passed a pointer to constant data that should not be modified. Either use `void foo(const char *string)` or arrange to use something other than a string literal (e.g. `char data[] = "String";` and call `foo(data + i);`. – Jonathan Leffler Mar 28 '23 at 13:51
  • Just add it to the sample String. So, I would like to pass "String " as the loop increments. – Mostack Mar 28 '23 at 13:51
  • 1
    Have a look at the duplicate post I linked. You need to solve two problems: 1. How to convert your int value into a string, and 2. How to concatenate your passed in string with the string of your int value. – Robert Harvey Mar 28 '23 at 13:52
  • 2
    That sounds like a case for `snprintf()` —— `char buffer[16]; for (int i = 0; i < n; i++) { snprintf(buffer, sizeof(buffer), "String %d", i); foo(buffer); }`. C does not provide string primitives like scripting languages do. Using `foo("String" + i)` passes the pointer to the `S`, then to the `t`, then to the `r`, … as `i` increases from 0. – Jonathan Leffler Mar 28 '23 at 13:53
  • Oof. I have some bad news for you. This isn't Python. Robert's link is probably what you are looking for. Just for clarifications sake, `char*` is not a pointer to a string. It's a pointer to some bytes. We may say a bunch of bytes the ends in a null terminator (zero byte), is a string, but there is no native string in C. – Jason Mar 28 '23 at 13:54
  • That seems to do the trick. Thanks, @JonathanLeffler – Mostack Mar 28 '23 at 13:59

0 Answers0