【发布时间】:2016-08-19 02:42:00
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int string_cmp(const void *p, const void *q);
int main(int argc, char **argv)
{
int i; // variable
char **words_array = malloc(sizeof(char*)*(argc+1)); // sets new array to hold the words
char *p; // another char pointer array
p = *words_array; // set both equal to eachother
for(; *p < (argc - 1); p++) // for loop
{
p = malloc(strlen(*argv) + 1); // determines size based on user input
argv++; // increments
strcpy(p++, *argv); // copies words to the new array
}
p = NULL; // resets p
qsort(words_array, argc-1, sizeof(char *), string_cmp); // sorts the array
for(i = 0; i < argc - 1; i++){ // for loop to print properly
printf("%s ", words_array[i]);
}
printf("\n");
return 0;
}
int string_cmp (const void *p, const void *q) // compares the two different strings and returns a value
{
const char *value = *(const char**)p;
const char *value_two = *(const char**)q;
return strcmp(value, value_two);
}
所以我的程序应该接受命令行参数并返回它们使用 Qsort 排序。示例是“./a.out 你好黑暗我的老朋友应该作为黑暗朋友你好我的老朋友返回。我没有收到任何编译器错误但是我得到一个分段错误,我不知道如何解决这个问题我的指针算术。
【问题讨论】:
-
p = *words_array;words_array的 malloc 在哪里? -
你为什么将 words_array 声明为指向指针的指针?
-
@sjsam malloc 在声明 **words_array 时就在那里
-
@RamblinRose,有没有更简单的方法或者我该如何解决?
-
使用不确定的对象值的未定义行为。
标签: c pointers segmentation-fault pointer-arithmetic