【问题标题】:Copy contents of non null terminated char array into another char array将非空终止字符数组的内容复制到另一个字符数组中
【发布时间】:2015-03-29 00:03:17
【问题描述】:

我有一个结构数组,每个结构都有一个 char 数组和一个 int。

typedef struct {
    int id; //Each struct has an id
    char input[80]; //Each struct has a char array
    } inpstruct;

inpstruct history[10]; //Array of structs is created

我有另一个包含用户输入的 char 数组

char inputBuffer[80];

用户输入一个单词,后跟\n 字符。例如,inputBuffer 将包含 3 个字符:'l''s''\n'

我想将inputBuffer中的所有字符复制到history[index].input

我尝试过使用:

strcpy(history[index].input, inputBuffer);

但由于inputBuffer 不是空终止的,它不起作用。如何将inputBuffer 中的所有字符复制到history[index].input 中?

【问题讨论】:

  • length = read(STDIN_FILENO, inputBuffer, 80);
  • 定义it does not work
  • strcpy 是,你猜对了,用于 c 风格的 0 终止字符串。你想复制原始内存,因此使用memcpy
  • 使用memcpy(history[index].input, inputBuffer, sizeof inputBuffer);我得到错误'memcpy'调用对'char'类型的对象进行操作,而大小基于不同的'char *'类型
  • 似乎您没有将数组传递给sizeof,而是一个指向其内容的指针。可能是由于函数调用中的数组衰减?

标签: c arrays strcpy


【解决方案1】:

你想memcpy

memcpy(history[index].input, inputBuffer, sizeof(inputBuffer)*sizeof(inputBuffer[0]));

【讨论】:

  • 我收到警告warning: sizeof on array function parameter will return size of 'char *' instead of 'char []',然后收到错误malloc: *** error for object 0x10ae0d074: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug
  • 您需要展示更多代码。 sizeof 操作符应该和我展示的完全一样。但是,如果元素是传递给函数的指针,那么sizeof 将不起作用(这是您的错误消息所暗示的),您将不得不对大小进行硬编码。仅供参考 - malloc 错误与您共享的代码无关,并建议您尝试释放以前未由 malloc() 分配的指针。
  • 是的 inputBuffer 正在被传递到一个 void 方法中,其中 memcpy 正在完成。我还将大小硬编码为 80,但运行时仍然出现 malloc 错误
  • 正如我所说的 malloc 错误是另一锅鱼。您的代码正在调用 free() 并使用以前未由 malloc() 分配的内存。运行调试器以找到代码中发生这种情况的确切位置并进行修复。
猜你喜欢
  • 2011-06-09
  • 2020-09-04
  • 2013-10-22
  • 1970-01-01
  • 2013-08-28
  • 1970-01-01
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
相关资源
最近更新 更多