#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 你好黑暗我的老 friend 应该作为黑暗 friend 你好我的老 friend 返回。我没有收到任何编译器错误,但我收到了段错误,我不知道如何解决这个问题我的指针算术。
最佳答案
您正在递增双指针(argv),即;
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
}
所以将其更改为 (*argv)++
关于c - 指针算术分段问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36845120/