【发布时间】: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