簡體   English   中英

字符級聯和內存重新分配

[英]Char concatenation and memory reallocation

我正在嘗試將單個數字連接到字符串:

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

int main() {

  char *test="";
  int i;

  for (i = 0; i < 10; i++) 
    char *ic;
    ic = malloc(2);
    sprintf(ic, "%d", i);

    // printf("%d\n", strlen(test));

    if (strlen(test) == 0) 
      test = malloc(strlen(ic));
      strcpy(test, ic);
    } else {
      realloc(test, strlen(test) + strlen(ic));
      strcat(test, ic);
    }

  }
  printf("%s\n", test);
  // printf("%c\n", test);
  free(test);
  test = NULL;
  return 0;
}

我的目標是最終的printf ("%s", test)0123456789

請記住,字符串以空字符結尾。 為字符串分配內存時,必須為null添加一個額外的字節。 因此,您需要為每個malloc()realloc()調用加1。 例如:

test = malloc(strlen(ic) + 1);

還要記住,還允許realloc()將變量“移動”到內存中的新位置。 為了找到足夠的連續未分配空間,可能需要這樣做。 如果無法分配所需的內存,它也可以返回NULL ,因此應按以下方式調用它:

char *new_mem = realloc(test, strlen(test) + strlen(ic) + 1);
if (new_mem == NULL) {
  // Not enough memory; exit with an error message.
} else {
  test = new_mem;
}

一些問題:

  1. char *test=""; -將測試指向恆定的C字符串。 您無需編寫代碼,但這很危險,並且會在C ++中進行編譯。 ""的類型為const char*
  2. strlen返回字符串的長度,而不是緩沖區的大小。 您需要添加+1以包含NULL字符。 這是您最大的問題。
  3. 應該在堆棧上分配一個已知的簡短的固定大小的小緩沖區,如ic 一個簡單的char數組。 您還忘記了free()它。

暫無
暫無

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

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