附加两个没有 str 函数的字符串

Appending two strings without str functions

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

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

在这种情况下,我目前有代码声明一个结构并将东西设置为结构内容的值你好我进入我的函数并检查数据是否person is passing 不为空。我创建了一个名为 append 的新字符串结构,并将 realloc 内存添加到先前 "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;
}

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

  1. 您在名为 append 的函数中使用了变量名 append,这是错误的形式。我什至不确定是否编译。
  2. = 运算符是在实际需要 == 时使用的。前者是为了 分配,因此条件将始终为真。
  3. realloc() 用于 b->stuff,这是一个 char*,但你将它转换为 String*。这在技术上可能可行,但它的形式确实很糟糕。
  4. b->stuff 上使用 realloc() 后,您仍然使用指针 b->stuff,即使 realloc() 使传递的指针无效并且 returns 一个新指针一.
  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 '[=10=]' 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;
}