c - 从函数制作 char 向量
问题描述
假设我想从给定的字符串(作为函数的参数)创建新字符串并返回新字符串。
在 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的地址修改堆栈,并且您还需要放置终止的 null char 所以我只需将 1 添加到要复制的 char 数
注意使用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)
推荐阅读
- vue.js - Service Worker:如果由于网络问题导致获取 POST 失败,则从 SW 中注册同步
- git - 是否可以在 Github 的公共存储库中创建私有分支?
- hosting - Hostinger wordpres mutlisite网络不在子域上工作,但它正在工作子目录
- react-native - 跨文本组件的水平线
- c++ - 如何在 CMake 中打印变量?
- c# - Sync over Async - 线程使用说明
- ruby-on-rails - Rails 引擎教程警告(配置引擎)
- r - 如何从每行具有不同列数的文件中读取前四列到数据框中
- php - 在 WooCommerce 单品页面上发布显示运输数据
- zxing - 将 Zxing 库与 Jetpack 组合使用