c - append 两个没有 str 函数的字符串

标签 c string struct append

我在尝试弄清楚如何将 char 指针 c append 到现有结构 String 时遇到问题。我希望能够接受这样的输入(考虑一个预定义的 Struct,其值为“Hello”) append(test,"world") 当我尝试使用 strcat strcpy 我收到错误消息,因为结构 String 不是可用于此函数的有效类型。

如何在不使用 str 函数的情况下追加?

我目前有代码声明一个结构并将东西设置为结构内容的值在这种情况下你好我进入我的函数并检查该人传递的数据是否不是无效的。我创建了一个名为 append 和 realloc 的新 String Struct 内存到先前“stuff”的新大小加上 *c 的值。我是否应该使用 for 循环将点 [i] 处的 *c 的内容放入 append 的末尾?

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

typedef struct strstf {
    char  * stuff;
    size_t  length;
} String;

String * append(String * b, const char * c) {
    String * append;
    if (c != NULL) {
        /* creates memory the size of the original string buffer and the added string */
        b->stuff realloc(strlen(c) + strlen(b->stuff) + 1);
        strcpy(append, b->stuff);
        strcat(append, c);
        return append;  
    }
    if (append->stuff == NULL) {
        free(append);  
        return NULL;
    }
    return append;
}

最佳答案

您的代码有很多错误。这是我在 bat 右侧注意到的:

  1. 您在名为 append 的函数中使用了变量名 append,这是错误的形式。我什至不确定是否可以编译。
  2. = 运算符是在实际需要 == 时使用的。前者是为了 分配,因此条件将始终为真。
  3. realloc() 用于 b->stuff,它是一个 char*,但是你将它转换为一个 字符串*。这在技术上可能可行,但它确实是一种糟糕的形式。
  4. b->stuff 上使用 realloc() 后,即使 realloc,您仍然使用指针 b->stuff () 使传递给它的指针无效并返回一个新指针。
  5. strcpystrcat 在指向类型 struct strstf 的指针上,当它们都需要 char*

以下代码有效。您只需要记住释放指针 result result->stuff。这是内存泄漏的一个非常容易发生的地方。

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

typedef struct strstf {
    char   *stuff;   
    size_t  length;   
} String;

String *append(String *b, const char *c){
    String* result = malloc(sizeof(String)); /* allocate memory for the resulting string */

     if (c != NULL && b != NULL && b->stuff != NULL) { /* make sure nothing is NULL */
        result->length = strlen(c) + b->length; /* calculate the length of the new string */
        result->stuff = malloc(result->length + 1); /* allocate the memory for the char array (plus '\0' char) */
        strcpy(result->stuff, b->stuff); /* copy the first to the result */
        strcat(result->stuff, c); /* append the second to the first */
        return result;  /* return the result */
    }
    return NULL; /* something went wrong */
}

int main(int argc, char* argv[]) {
    String first;
    String* result;
    if (argc != 3) {
        printf("The syntax of the command was incorrect.\n");
        return 1;
    }

    first.stuff = argv[1];
    first.length = strlen(argv[1]);

    result = append(&first, argv[2]);

    printf("Result: %s\n", result->stuff);

    free(result->stuff); /* DON'T FORGET THIS */
    free(result);

    return 0;
}

关于c - append 两个没有 str 函数的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30962322/

相关文章:

php - 在 PHP 中解析单词

结构中数组的 C Malloc

c - accept() 一直返回 0

javascript - .替换超过某一点的所有内容

c - C 中的父/子和管道,子-父通信

php - 修剪空白

c++ - 用于聚合结构初始化时的三元运算符整数表达式的类型

c - 未提及的结构字段是否*总是*初始化为零(即当结构在堆栈上时)?

c - 如何在二维数组中找到匹配值的最快方法

比较这些二叉树节点实现的空间复杂度?