【问题标题】:simple strcpy from string to string crashes entire programme [duplicate]从字符串到字符串的简单strcpy会使整个程序崩溃[重复]
【发布时间】:2021-10-08 12:24:50
【问题描述】:

对不起,如果这是一个常见问题,但我不确定为什么这段代码不会输出任何内容:

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

int main()
{
char source[] = "hello world!";

char **destination;

strcpy(destination[0], source);

puts(destination[0]);
puts("string copied!");

return 0;
}

看起来它在strcpy() 崩溃,因为“字符串已复制!”也不会出现在终端中

【问题讨论】:

  • 你认为复制的字符串会放在哪里? destination[0] 指向什么内存空间?您需要分配或定义一个缓冲区并将该地址提供给您的目标。
  • 到目前为止,destination 甚至指向什么?我建议decent book 和一些关于指针的部分的质量时间。指针对于在 C 语言中做几乎任何事情都是非常基础的。你不只是想学习它;你还想学习它。你需要掌握它。
  • 欢迎来到 SO。您的编译器是否告诉您有关使用 destination 而不进行初始化的信息?您应该始终注意编译器发出的所有警告。
  • 按顺序学习数组,然后是指针,然后是字符串。
  • @Nagev 评论并不是此类代码的正确位置。

标签: c string strcpy


【解决方案1】:

您的问题是char **destination 是一个指向指针的空指针。 destination[0] 绝对没有任何意义。

这是你实际的做法:

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

int main()
{
  char source[] = "hello world!";

  char destination[100];

  strcpy(destination, source);

  puts(destination);
  puts("string copied!");

  return 0;
}

或者如果您想动态确定目的地的大小:

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

int main()
{
  char source[] = "hello world!";

  char *destination = malloc(strlen(source) * sizeof(char)+1); // +1 because of null character

  strcpy(destination, source);

  puts(destination);
  puts("string copied!");


  free(destination); // IMPORTANT!!!!
  return 0;
}

确保您free(destination),因为它是在堆上分配的,因此必须手动释放。

【讨论】:

    猜你喜欢
    • 2012-11-17
    • 2020-02-16
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    相关资源
    最近更新 更多