簡體   English   中英

如何將字符串附加到字符串中,在C中動態分配內存?

[英]how can I append a char to a string allocating memory dynamically in C?

我寫了這段代碼,但是在字符串的開頭插入了垃圾:

void append(char *s, char c) {
    int len = strlen(s);
    s[len] = c;
    s[len + 1] = '\0';
}

int main(void) {
    char c, *s;
    int i = 0;
    s = malloc(sizeof(char));
    while ((c = getchar()) != '\n') {
        i++;
        s = realloc(s, i * sizeof(char));
        append(s, c);
    }   
    printf("\n%s",s);   
}

我該怎么做?

您的代碼中存在多個問題:

  • 迭代直到從標准輸入流中讀取換行符( '\\n' )。 如果在讀取換行符之前發生文件結尾,則會導致無限循環,如果從空文件重定向標准輸入,則會發生這種情況。
  • c應定義為int以便您可以正確測試EOF
  • s應該始終以null結尾,你必須在malloc()之后將第一個字節設置為'\\0' ,因為這個函數沒有初始化它分配的內存。
  • i應該初始化為1所以第一個realloc()將數組擴展為1等。編碼后,你的數組是一個太短的字節,無法容納額外的字符。
  • 你應該檢查內存分配失敗。
  • 為了好的風格,你應該在退出程序之前釋放分配的內存
  • main()應該返回一個int ,最好是0才能成功。

這是一個更正版本:

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

/* append a character to a string, assuming s points to an array with enough space */
void append(char *s, char c) {
    size_t len = strlen(s);
    s[len] = c;
    s[len + 1] = '\0';
}

int main(void) {
    int c;
    char *s;
    size_t i = 1;
    s = malloc(i * sizeof(char));
    if (s == NULL) {
        printf("memory allocation failure\n");
        return 1;
    }
    *s = '\0';
    while ((c = getchar()) != EOF && c != '\n') {
        i++;
        s = realloc(s, i * sizeof(char));
        if (s == NULL) {
            printf("memory allocation failure\n");
            return 1;
        }
        append(s, c);
    }
    printf("%s\n", s);
    free(s);
    return 0;
}

當你調用strlen它會搜索'\\0'字符來結束字符串。 你的字符串中沒有這個字符,因為strlen的行為是不可預測的。 你的append功能非常好。 另外,一件小事,你需要添加return 0; 到你的主要功能。 如果是0, i應該從1開始。以下是它的外觀:

int main(void){
   char *s;
   size_t i = 1;
   s = malloc (i * sizeof(char));//Just for fun. The i is not needed.
   if(s == NULL) {
   fprintf(stderr, "Coul'd not allocate enough memory");
   return 1;
   }
   s[0] = '\0';
   for(char c = getchar(); c != '\n' && c != EOF; c = getchar()) {//it is not needed in this case to store the result as an int.
      i++;
      s = realloc (s,i * sizeof(char) );
      if(s == NULL) {
             fprintf(stderr, "Coul'd not allocate enough memory");
             return 1;
      }
      append (s,c);
    }   
printf("%s\n",s);   
return 0;
}

感謝您幫助我改進代碼(以及我的英語)的評論。 我並不完美 :)

內部realloc需要多分配一個元素(對於尾隨\\0 ),你必須在開始循環之前初始化s[0] = '\\0'

順便說一句,你可以用strcat()替換你的append或者像它一樣寫

size_t i = 0;
s = malloc(1);
/* TODO: check for s != NULL */
while ((c = getchar()) != '\n') {
        s[i] = c;
        i++;
        s = realloc(s, i + 1);
        /* TODO: check for s != NULL */
}
s[i] = '\0';

暫無
暫無

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

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