【问题标题】:Copy an array of string in C在C中复制一个字符串数组
【发布时间】:2017-09-16 12:54:39
【问题描述】:

我正在制作一个程序,根据一些规则对输入的单词进行排序。

为了对齐它们,我想通过使用 memcpy 将“words”复制到“tmp”来使用和更改“tmp”。

我试图将 tmp 声明为双指针或数组,但我遇到的唯一一个是分段错误。

我怎样才能复制所有的“单词”?

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

#define MAX_WORD_LEN 30

int getInput(char*** words) {
  int count;
  int i;
  char buffer[MAX_WORD_LEN+1];

  printf("Enter the number of words: ");
  scanf("%d", &count);
  *words = malloc(count * sizeof(char*));
  printf("Enter the words: ");
  for (i = 0; i < count; i++) {
    (*words)[i] = malloc((MAX_WORD_LEN + 1) * sizeof(char));
    scanf("%s", buffer);
    strcpy((*words)[i], buffer);
  }
  return count;
}

void solve() {
  int count;
  int i;
  char ** words;
  count = getInput(&words);

  char ** tmp = malloc(count* sizeof(char*));
  memcpy(tmp, words, sizeof(char *));
}

void main() {
  solve();
  return;
}

【问题讨论】:

  • 为什么要复制到tmp?不能直接用words吗?另外,请记住您正在复制 指针 而不是它们指向的内容(字符串)本身。最后,在getInput 中,您不需要buffer 数组,而是将scanf 直接放入(*words)[i]
  • @Someprogrammerdude 感谢您的评论。其实我想重新排列它们,比如 7531246。把第一个放在中间,第二个放在第一个的右边,第三个放在第一个的左边...
  • void main() --> int main(void).
  • 这段代码没有多大意义。先试试不带函数的写吧。

标签: c arrays pointers memcpy strcpy


【解决方案1】:

在函数solve() 内部,您并没有增加指针以将下一个字符串存储在内存中:

memcpy(tmp, words, sizeof(char *));

这里你没有增加指针来存储下一个字符串。

你需要做的是:
for(i=0; i<count; i++) memcpy(&tmp[i], &words[i], sizeof(char *));

【讨论】:

    【解决方案2】:

    您首先创建了一个指针数组,然后为每个新单词调用 malloc。

    for (i = 0; i < count; i++) {
        (*words)[i] = malloc((MAX_WORD_LEN + 1) * sizeof(char));
        scanf("%s", buffer);
        strcpy((*words)[i], buffer);
      }
    

    (你可以直接扫描到单词而不使用缓冲区)

    请注意,没有任何东西可以保证所有这些段的内存分配是连续的。

    如果你想复制所有的单词,你必须对 tmp 做同样的事情。

     char ** tmp = malloc(count * sizeof(char*));
      for (i = 0; i < count; i++) {
        tmp[i] = malloc((MAX_WORD_LEN + 1) * sizeof(char));
        memcpy(tmp[i], words[i], sizeof(MAX_WORD_LEN + 1));
      }
    

    【讨论】:

    • 你的答案和上面的答案有什么区别?
    • 哪个上面的答案?
    猜你喜欢
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 2013-02-16
    • 2020-09-04
    • 2015-06-06
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    相关资源
    最近更新 更多