-2

The following code is a mockup, but I have not get to pass this to a function, one way or another it throws an error (I know it should be simple, I am learning)

int main()
{
    long a[] = {10, 20, 30, 40};

    // mockup...
    char s[] = "";
    for (size_t i = 0; i < (sizeof(a) / sizeof(long)); i++)
    {
        sprintf(&s[strlen(s)], "%d ", a[i]);
    }
    printf("array: %s\n", s); // OK : ), outpput: array: 10 20 30 40

    // ?
    printf("array: %s\n", array_to_string(a));

    return 0;
}
  • `char s[] = "";` only has enough space for 1 char. You need a bigger buffer. For example: `char s[128] = "";` – 001 Sep 01 '21 at 17:51
  • You say it throws an error. What is the error? – jarmod Sep 01 '21 at 17:52
  • The code below *mockup...* does not have error. The question is how to write **array_to_string()** – Alexandra Danith Ansley Sep 01 '21 at 18:02
  • What is your expected output? – starboy_jb Sep 01 '21 at 18:17
  • 2
    Returning a string in C is one of those things where people from other languages wonder "how can this be so hard?" The fact that strings aren't first-class objects, and that the programmer is responsible for memory management, make it trickier than you might guess. There are several possible approaches with various pros and cons, none of them perfect or completely trivial. See https://stackoverflow.com/questions/1496313/returning-a-c-string-from-a-function for a rundown. – Nate Eldredge Sep 01 '21 at 20:08
  • PS. I have not understood why some people mark questions as *it is unclear or not useful*. For me the question and the answer were very useful. – Alexandra Danith Ansley Sep 01 '21 at 21:39

1 Answers1

1

You will probably want your function to take 4 parameters:

  1. The array of numbers
  2. The count of those numbers
  3. A char buffer to hold the string
  4. The size of the buffer.

And it should return a pointer to the string buffer:

char * array_to_string(long array[], size_t array_length, char buffer[], size_t buffer_length) {
    // Fill in with your code
    return buffer;
}

Then you can call this like:

int main()
{
    long a[] = {10, 20, 30, 40};
    char buffer[128];
    printf("%s", array_to_string(a, sizeof(a)/sizeof(a[0]), buffer, sizeof(buffer)));
    return 0;
}

This can also be done with dynamic memory allocation which would avoid passing the char array to the function.

001
  • 13,291
  • 5
  • 35
  • 66