将整数数组转换为C中的字符数组

发布于 2025-01-31 09:18:26 字数 1417 浏览 3 评论 0原文

我需要知道如何将整数数组转换为C中的字符数组。 我有1000个元素int阵列,我将有4000个字节大小的字符阵列。 如何将每个整数元素填充到字符数组中,以便在打印时,将所有整数显示在单个字符串中。 示例:dsid_list [3] = {1000,1001,1002}; 那么char_dsid_array应该具有“ 100010011002” 以下是代码段,试图执行相同的代码。

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

int main()
{
        uint32_t dsid_count = 1000;

        printf("dsid_count:%lu\n",dsid_count);

        uint32_t dsid_list[dsid_count];
        uint32_t i;

        printf("start\n");
        for(i=0; i<dsid_count; i++) {
                dsid_list[i] = i;
        }
        printf("Size of dsid_list:%lu\n", sizeof(dsid_list));

        //char char_dsid_array[sizeof(dsid_list)];
        char *char_dsid_array = (char*)malloc(sizeof(dsid_list) + 1);
        
        i=0;
        char* temp = (char*)malloc(4);
        char* temp1 = char_dsid_array;
        for(i=0; i<dsid_count; i++) {
                sprintf(temp, "%lu", dsid_list[i]);
                if(i == 0) {
                        strcpy(char_dsid_array, temp);
                }
                else {
                        strcat(char_dsid_array, temp);
                }
                char_dsid_array = char_dsid_array + 4;
        }
        char_dsid_array = temp1;
        printf("DSID list: %s\n", char_dsid_array);

        free(char_dsid_array);
        free(temp1);
        free(temp);

        return 0;
}

I need to know how we can convert integer array to character array in C.
I have 1000 elements int array and I will have 4000 byte sized char array.
How to fill each integer elements into character array so that when printed all integers are shown in single string.
Example: dsid_list[3] = {1000, 1001, 1002};
Then char_dsid_array should have "100010011002"
Below is the code snippet trying to perform same.

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

int main()
{
        uint32_t dsid_count = 1000;

        printf("dsid_count:%lu\n",dsid_count);

        uint32_t dsid_list[dsid_count];
        uint32_t i;

        printf("start\n");
        for(i=0; i<dsid_count; i++) {
                dsid_list[i] = i;
        }
        printf("Size of dsid_list:%lu\n", sizeof(dsid_list));

        //char char_dsid_array[sizeof(dsid_list)];
        char *char_dsid_array = (char*)malloc(sizeof(dsid_list) + 1);
        
        i=0;
        char* temp = (char*)malloc(4);
        char* temp1 = char_dsid_array;
        for(i=0; i<dsid_count; i++) {
                sprintf(temp, "%lu", dsid_list[i]);
                if(i == 0) {
                        strcpy(char_dsid_array, temp);
                }
                else {
                        strcat(char_dsid_array, temp);
                }
                char_dsid_array = char_dsid_array + 4;
        }
        char_dsid_array = temp1;
        printf("DSID list: %s\n", char_dsid_array);

        free(char_dsid_array);
        free(temp1);
        free(temp);

        return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

刘备忘录 2025-02-07 09:18:26
  • 无论如何,uint32_t可以将值提取到4294967295(2 32 - 1),因此4 bytes字符空间不足以将该数字存储为字符串。

  • 幸运的是,您正在尝试使用范围中的数字来创建字符串[0..999]

  • 只需循环浏览数字,然后从sprintf()使用返回值字符串的后缀号。 sprintf()(&amp; printf()兄弟姐妹)返回成功写入目标的字符数。

// after malloc
    int slen = 0;
    for (int num = 0; num < dsid_count; ++num)
        slen += sprintf (char_dsid_array + slen, "%d", num);

    printf("DSID list: %s\n", char_dsid_array);
  • 但是,如果dsid确实大于数字1000,则需要分配足够的空间,例如1001010 x 1001代码> = 10010)字节,以使千ID在更安全的侧面。
  • 生成字符串完成后,请使用realloc()在必要时修剪未使用的内存,例如:
char* ptr = realloc (char_dsid_array, slen +1);
if (ptr) char_dsid_array = ptr;
else /* error handling */
  • Anyway, uint32_t can take values up to 4294967295 (232 - 1), so 4 bytes character space is not enough for storing that number as a string.

  • Luckily, you're trying to create string using numbers in range [0..999]

  • Just loop through the numbers and use return value from sprintf() to suffix numbers to the string. sprintf() (& printf() siblings) returns number of characters written to the target on success.

// after malloc
    int slen = 0;
    for (int num = 0; num < dsid_count; ++num)
        slen += sprintf (char_dsid_array + slen, "%d", num);

    printf("DSID list: %s\n", char_dsid_array);
  • However, if DSIDs are indeed larger than number1000, then you need allocate sufficient space like 10010 (10 x 1001 = 10010) bytes for thousand such IDs to be on the safer side.
  • Once done generating the string, use realloc() to trim unused memory if necessary, like:
char* ptr = realloc (char_dsid_array, slen +1);
if (ptr) char_dsid_array = ptr;
else /* error handling */
帝王念 2025-02-07 09:18:26

4个字符足以存储0到999之间整数的基本10字符串表示形式,但通常不足以存储任意int。您可以使用snprintf来计算生成字符串表示形式所需的空间数量。我建议在初始化数组,然后分配一次空间时累积所需的大小。例如:

#include <assert.h>
#include <stdio.h>
#include <inttypes.h>
#include <string.h>
#include <stdlib.h>
void * xmalloc(size_t s);

int
main(int argc, char **argv)
{
    size_t dsid_count = argc > 1 ? strtol(argv[1], NULL, 10) : 1000;
    size_t needed = 0;
    printf("dsid_count:%zu\n", dsid_count);

    uint32_t *dsid_list = xmalloc(dsid_count * sizeof *dsid_list);
    uint32_t i;

    for( size_t i = 0; i < dsid_count; i+= 1 ){
        dsid_list[i] = i;
        needed += snprintf(NULL, 0, "%" PRIu32, dsid_list[i]);
    }

    char *int_string = xmalloc(needed + 1);
    char *end = int_string;
    size_t avail = needed + 1;

    for( size_t i = 0; i < dsid_count; i+= 1 ){
        int s = snprintf(end, avail, "%" PRIu32, dsid_list[i]);
        end += s;
        avail -= s;
    }
    assert( end - int_string == needed );
    printf("%s\n", int_string);
}


void *
xmalloc(size_t s)
{
    void *rv = malloc(s);
    if( rv == NULL ){
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    return rv;
}

4 characters is enough to store the base-10 string representation of integers between 0 and 999, but in general it will no be enough to store an arbitrary int. You can use snprintf to compute the amount of space you need to generate a string representation. I would suggest accumulating the size you will need as you initialize the array and then allocate space once. eg:

#include <assert.h>
#include <stdio.h>
#include <inttypes.h>
#include <string.h>
#include <stdlib.h>
void * xmalloc(size_t s);

int
main(int argc, char **argv)
{
    size_t dsid_count = argc > 1 ? strtol(argv[1], NULL, 10) : 1000;
    size_t needed = 0;
    printf("dsid_count:%zu\n", dsid_count);

    uint32_t *dsid_list = xmalloc(dsid_count * sizeof *dsid_list);
    uint32_t i;

    for( size_t i = 0; i < dsid_count; i+= 1 ){
        dsid_list[i] = i;
        needed += snprintf(NULL, 0, "%" PRIu32, dsid_list[i]);
    }

    char *int_string = xmalloc(needed + 1);
    char *end = int_string;
    size_t avail = needed + 1;

    for( size_t i = 0; i < dsid_count; i+= 1 ){
        int s = snprintf(end, avail, "%" PRIu32, dsid_list[i]);
        end += s;
        avail -= s;
    }
    assert( end - int_string == needed );
    printf("%s\n", int_string);
}


void *
xmalloc(size_t s)
{
    void *rv = malloc(s);
    if( rv == NULL ){
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    return rv;
}
江心雾 2025-02-07 09:18:26
size_t print(char *buff, size_t size, int *array)
{
    size_t pos = 0;
    int len = 0;

    while(size--)
    {
        len = snprintf(buff + (!!buff) * pos, !!buff * INT_MAX, "%d", *array++);
        if(len < 0) { /* error andling */}
        pos += len;
    }
    return pos;
}

char *printIntArray(size_t size, int *array)
{
    char *string = malloc(print(NULL, size, array) + 1);

    if(string) print(string, size, array);
    return string;
}

int main(void)
{
    int array[3] = {1000, 1001, 1002};
    char *b;
    printf("\"%s\"\n", b = printIntArray(3, array));
    free(b);
}
size_t print(char *buff, size_t size, int *array)
{
    size_t pos = 0;
    int len = 0;

    while(size--)
    {
        len = snprintf(buff + (!!buff) * pos, !!buff * INT_MAX, "%d", *array++);
        if(len < 0) { /* error andling */}
        pos += len;
    }
    return pos;
}

char *printIntArray(size_t size, int *array)
{
    char *string = malloc(print(NULL, size, array) + 1);

    if(string) print(string, size, array);
    return string;
}

int main(void)
{
    int array[3] = {1000, 1001, 1002};
    char *b;
    printf("\"%s\"\n", b = printIntArray(3, array));
    free(b);
}
稳稳的幸福 2025-02-07 09:18:26

先生,下面有案例的代码示例:

dsid_list [3] = {1000,1001,1002};那么char_dsid_array应该有
“ 100010011002”

请注意一些安全的问题,在为阵列添加新整数之前,我们必须检查是否有足够的空间,如果有足够的空间,我将在consantate之前:

if(sizeof(my_list)&gt;(str_number(str_number)(str_number) ) + strlen(my_list)))

另一个可爱的安全求职者是snprintf,此功能改进sprintf以避免溢出。

Here's an online working code

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

#define INT_CHARS 11 // 5 should be enough, 1000-1999 span 4 digits + '\0', 11 bits are enough for biggest integer number

int main()
{
    int n;
    int length;
    char str_number[INT_CHARS]; // size should enoght to store all digits, null terminator,
    int dsid_list[3] = {1000, 1001, 1002};
    char my_list[4001]= "";

    length = sizeof(dsid_list) / sizeof(int);

    for(n = 0; n < length; n++)
    {
        snprintf(str_number, INT_CHARS, "%d", dsid_list[n]);
        if(sizeof(my_list) > (strlen(str_number) + strlen(my_list)))
        {
            strcat(my_list, str_number);
        }
        else
        {
            printf("Not enough space to store more data\n");
            break;
        }
    }
    printf("my list = %s", my_list);
}

Sir, down below there is code example for the case:

dsid_list[3] = {1000, 1001, 1002}; Then char_dsid_array should have
"100010011002"

Please note some secure issues, before add a new integer to the array we must check there is enough space, before concantenate I will if there is space enough:

if(sizeof(my_list) > (strlen(str_number) + strlen(my_list)))

Another cute security recourse is snprintf, this function improves sprintf to avoid overflow.

Here's an online working code link

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

#define INT_CHARS 11 // 5 should be enough, 1000-1999 span 4 digits + '\0', 11 bits are enough for biggest integer number

int main()
{
    int n;
    int length;
    char str_number[INT_CHARS]; // size should enoght to store all digits, null terminator,
    int dsid_list[3] = {1000, 1001, 1002};
    char my_list[4001]= "";

    length = sizeof(dsid_list) / sizeof(int);

    for(n = 0; n < length; n++)
    {
        snprintf(str_number, INT_CHARS, "%d", dsid_list[n]);
        if(sizeof(my_list) > (strlen(str_number) + strlen(my_list)))
        {
            strcat(my_list, str_number);
        }
        else
        {
            printf("Not enough space to store more data\n");
            break;
        }
    }
    printf("my list = %s", my_list);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文