c - 指针算术分段问题

标签 c pointers segmentation-fault pointer-arithmetic

 #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/

相关文章:

c++ - 当类及其方法存储在指针数组中时如何调用它

c - 运行循环 41881 次时出现段错误

C:删除第一个元素时双向链表中的段错误

c - 指针增量导致段错误

c - 为什么我的字符数组不起作用?

c - 结构段错误 : 11. 无法重新分配首先初始化为 null 的结构中的值

在C中从二进制文件转换为十六进制

C - fgets 返回损坏的数据

c++ - 我能保证所有指针都具有相同的字节大小吗?

c - 如何测试变量是否在一组值中?