簡體   English   中英

指向char指針字符串的整數數組

[英]integer array to char pointer string

我正在嘗試將int數組轉換為char指針字符串(將數組值轉換為十六進制)。我正在使用代碼塊編輯器。
所以,

                           int arr[4] = {30, 40, 15, 205};

應該轉換為

                            char *str =  "1e280fcd";

為此,我編寫了以下程序:

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

int main()
{
    char *cur_str, *prev_str;
    char *comp_str, *comp_str_copy;
    int arr[] = {30,40,15,205}, i, j, arr_length;
    arr_length = (sizeof(arr)/sizeof(arr[0]));
    prev_str = malloc(sizeof(0));
    cur_str = malloc(sizeof(0));
    comp_str = malloc(sizeof(0));
    for(i=0;i<arr_length;i++)
    {
        cur_str = malloc(2);
        sprintf(cur_str,"%02x",arr[i]);

        comp_str = malloc(sizeof(cur_str)+sizeof(prev_str));
        sprintf(comp_str,"%s%s",prev_str,cur_str);
        printf("%s\n",comp_str);

        free(prev_str);
        prev_str = malloc(sizeof(comp_str));
        sprintf(prev_str,"%s",comp_str);

        if(i==(arr_length-1)){
            comp_str_copy = malloc(sizeof(comp_str));
            sprintf(comp_str_copy,"%s",comp_str);
        }

        free(comp_str);
        free(cur_str);
    }
    printf("%s %d\n",comp_str_copy,strlen(comp_str_copy));
    return 0;
}

該程序的輸出為

  • 分割錯誤或
  • 初始位置具有垃圾值的字符串

在此處輸入圖片說明

在此處輸入圖片說明

我已經在不同的在線編譯器上運行了相同的程序。 它們都給出正確的字符串作為輸出。我是在使用編輯器還是問題或內存管理方法?

    cur_str = malloc(2);
    sprintf(cur_str,"%02x",arr[i]);

sprintf會寫3個字符,包括最后一個空字符,而您只分配了2個

comp_str = malloc(sizeof(cur_str)+sizeof(prev_str));

分配長度不正確,因為size_of不返回您期望的值,必須是

comp_str = malloc(strlen(cur_str)+strlen(prev_str)+1);

但是當然prev_strprev_str也是正確的字符串,事實並非如此

這兩個malloc將產生內存泄漏,因為沒有空閑空間(也不使用)

cur_str = malloc(sizeof(0));
comp_str = malloc(sizeof(0));

為什么不使用realloc增加prev_str的大小?

注意最終所需的大小很容易知道: sizeof(arr)/sizeof(arr[0]) * 2 + 1如果數字限制為255(六位數為2位)

提案(不假設所有數字<256):

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

int main()
{
    int arr[] = {30,40,15,205};
    size_t arr_length = sizeof(arr)/sizeof(arr[0]);
    size_t i;
    size_t sz = 0;
    char * r = malloc(0);

    for (i=0; i!= arr_length; ++i)
    {
      char s[20];
      int l = sprintf(s, "%02x",arr[i]);

      r = realloc(r, sz + l + 1);
      strcpy(r + sz, s);
      sz += l;
    }
    printf("%s %d\n", r, sz);
    free(r);
    return 0;
}

編譯和執行:

pi@raspberrypi:/tmp $ gcc -g -pedantic -Wextra a.c
pi@raspberrypi:/tmp $ ./a.out
1e280fcd 8

valgrind下執行

pi@raspberrypi:/tmp $ valgrind ./a.out
==2985== Memcheck, a memory error detector
==2985== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==2985== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==2985== Command: ./a.out
==2985== 
1e280fcd 8
==2985== 
==2985== HEAP SUMMARY:
==2985==     in use at exit: 0 bytes in 0 blocks
==2985==   total heap usage: 6 allocs, 6 frees, 1,048 bytes allocated
==2985== 
==2985== All heap blocks were freed -- no leaks are possible
==2985== 
==2985== For counts of detected and suppressed errors, rerun with: -v
==2985== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)

一個簡單的任務需要大量的動態內存分配。 如果數組和字符串將保持“小”狀態,則可以使用堆棧:

#include <assert.h>
#include <stdio.h>

int main() {
    int const arr[] = {30, 40, 15, 205};
    int const arr_length = sizeof(arr) / sizeof(arr[0]);
    char str[2 * arr_length + 1];
    int len = 0;
    for (int i = 0; i < arr_length; i++) {
        len += sprintf(&str[len], "%02x", arr[i]);
    }
    assert(len == 2 * arr_length);
    printf("%s %d\n", str, len);
    return 0;
}

但是,如果您確實需要動態字符串,即char *str只需修改char str[2 * arr_length + 1];

char *str = malloc(2 * arr_length + 1);

並添加free(str);

注意:所有這些都假定您的整數數組值小於256。

以下建議的代碼:

  1. 消除了不必要的代碼邏輯
  2. 消除不必要的變量
  3. 消除了不必要的動態內存使用
  4. 干凈地編譯
  5. 不分段故障
  6. 執行所需的功能
  7. 請注意, strlen()返回size_t ,而不是int
  8. 請注意, sizeof()返回的是size_t而不是int
  9. 將數組arr[]的長度乘以2以計算顯示轉換后的數組所需的字符數
  10. 將1加到所計算的長度以允許尾隨NUL字節
  11. 以必要的順序列出變量,以便在需要時始終可以使用特定的參數

現在,建議的代碼:

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

int main( void )
{
    int arr[] = {30,40,15,205};
    char comp_str[ sizeof( arr )*2 +1 ] = {'\0'};  

    size_t arr_length = (sizeof(arr)/sizeof(arr[0]));

    for( size_t i=0; i<arr_length; i++ )
    {          
        sprintf( comp_str,"%s%02x", comp_str, arr[i] );
        printf("%s\n",comp_str);
    }
}

運行建議的代碼將導致:

1e
1e28
1e280f
1e280fcd

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM