Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,292 questions

55,012 answers

573 users

How to transform an array of integers into a string with C

1 Answer

0 votes
#include <stdio.h>

int transform_ints_to_string(int const* arr, int arr_size, char* buf, int buf_size) {
    int total_size = 0;

    for (; arr_size; arr_size--) {
        int length = snprintf(buf, buf_size, "%5d", *arr++);

        if (length >= buf_size) {
            return -1;
        }

        total_size += length;
        buf += length;
        buf_size -= length;
    }

    return total_size;
}

int main()
{
    char buf[128] = "";
    int arr[] = { 56, 8, 12, 908, 1046 };
    int arr_size = sizeof(arr) / sizeof(arr[0]);

    if (transform_ints_to_string(arr, arr_size, buf, sizeof buf) == -1) {
        puts("not enough space in buf");
    }
    else {
        printf("%s\n", buf);
    }

    return 0;
}



/*
run:

   56    8   12  908 1046

*/

 



answered Jul 31, 2024 by avibootz
...