c - 如何将字符串分配给 char* 指针?

标签 c arrays string pointers char

我是 C 新手,我花了 2 个小时才解决这个问题。

void helper(char* a, char* b){
    a = malloc(strlen(b));
    memcpy(a, b, strlen(b));
    printf("%s %s\n", a, b);
}

int main(){
    char* b = "hello";
    char* a;
    helper(a, b);
    printf("%s", a);
}

a始终为null。有什么我错过的吗?

最佳答案

main()中,ab是指针。

helper(a, b);helper() 提供指针 a 的副本和指针 b 的副本 作为调用 helper() 的一部分。

函数完成。

调用 helper(a, b) 不会更新/更改 main() 中的 ab 也没有改变。

<小时/>

代码需要一种新方法,其中有几种好的方法。示例:使用 helper2() 的返回值。

char *helper2(const char *source);

int main(void) {
  const char* b = "hello";
  char* a = helper2(b);
  printf("<%s>", a);
  free(a);
}

现在创建helper2()。代码模板如下:

#include <...>      // whats includes are needed.
#include <...>      
char *helper2(const char *source) {
  size_t size_needed = ....; // length + 1 for the null character
  char *destination = ...'   // allocate
  if (destination ...) {     // Successful allocation? 
    memcpy(destination, ...., ...); // copy - include null character
  }
  return ...                        // What should be returned here?
}  

关于c - 如何将字符串分配给 char* 指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41175504/

相关文章:

c - 利用缓冲区溢出读取操作

javascript - React - 遍历数组 - 未定义的映射

ios - 如何从 UITableView 中的数组中获取用户选择的值并将该值传递给服务器

java - C 中的命令行参数导致段错误?

c - 在 ubuntu 终端窗口中运行文件之前如何消除使用 "./"的需要?

c++ - LTO for clang 可以跨 C 和 C++ 方法优化吗

c - 为什么有些系统库需要 -l 选项,而另一些则不需要?

java - JSONArray 类型的 add(String) 方法未定义

c# - 从字符串转换日期时间的语法错误

C++,从 ‘char’ 到 ‘const char*’ 的无效转换