我在尝试弄清楚如何将 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 右侧注意到的:
- 您在名为
append
的函数中使用了变量名append
,这是错误的形式。我什至不确定是否可以编译。 =
运算符是在实际需要==
时使用的。前者是为了 分配,因此条件将始终为真。realloc()
用于b->stuff
,它是一个char*
,但是你将它转换为一个字符串*
。这在技术上可能可行,但它确实是一种糟糕的形式。- 在
b->stuff
上使用realloc()
后,即使realloc,您仍然使用指针
使传递给它的指针无效并返回一个新指针。b->stuff
() strcpy
和strcat
在指向类型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/