gpt4 book ai didi

c - 从函数创建字符 vector

转载 作者:太空宇宙 更新时间:2023-11-04 07:48:41 25 4
gpt4 key购买 nike

假设我想从给定的字符串(作为函数的参数)创建新字符串并返回新字符串。

当在 main 中调用该方法时,从未生成新字符串,我不明白为什么。

这是我在 main 之外的函数中的代码:

char* new_name(char* name)
{
char* res = (char*)malloc(strlen("recv") + strlen(name));
if(res == null)
{
return null;
}

else
{
memcpy(&res, "recv_", strlen("recv_"));
strcat(res, name);
}
return res;
}

主要是我有:

char * result = new_name(name);

定义和给出“名称”的地方。

最佳答案

  char* res = (char*)malloc(strlen("recv") + strlen(name));

由于后面的代码,您需要为“recv_”而不是“recv”分配空间,并再分配 1 个空间来放置终止空字符,所以

char* res = (char*)malloc(strlen("recv_") + strlen(name) + 1);

 if(res == null)
{
return null;
}

null 必须是 NULL

memcpy(&res, "recv_", strlen("recv_"));

必须是

memcpy(res, "recv_", strlen("recv_") + 1);

否则你不修改分配的数组,而是从变量 res 的地址修改堆栈,并且你还需要放置终止空字符,所以我只需将 char 的数量加 1复制

请注意使用 strcpy 是否更简单:strcpy(res, "recv_")


示例:

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

char* new_name(char* name)
{
char* res = (char*)malloc(strlen("recv_") + strlen(name) + 1);

if(res == NULL)
{
return NULL;
}

else
{
memcpy(res, "recv_", strlen("recv_") + 1); /* or strcpy(res, "recv_"); */
strcat(res, name);
}
return res;
}

int main()
{

char * result = new_name("foo");

printf("'%s'\n", result);
free(result);
return 0;
}

编译和执行:

pi@raspberrypi:~ $ gcc -pedantic -Wall -Wextra m.c
pi@raspberrypi:~ $ ./a.out
'recv_foo'

valgrind 下执行:

pi@raspberrypi:~ $ valgrind ./a.out
==22335== Memcheck, a memory error detector
==22335== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==22335== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==22335== Command: ./a.out
==22335==
'recv_foo'
==22335==
==22335== HEAP SUMMARY:
==22335== in use at exit: 0 bytes in 0 blocks
==22335== total heap usage: 2 allocs, 2 frees, 1,033 bytes allocated
==22335==
==22335== All heap blocks were freed -- no leaks are possible
==22335==
==22335== For counts of detected and suppressed errors, rerun with: -v
==22335== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)

关于c - 从函数创建字符 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55289394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com