c - 如何将字符串数组传递给该程序中的函数?

标签 c arrays c-strings

我是 C 语言的初学者,我们在类里面有一个作业,需要获取给定的字符串列表,将它们放入字符串数组中,然后将其传递给用户定义的排序函数,该函数按字母顺序打印它们。每当我运行我的代码时,它都不会给出任何编译器错误,但它也会在运行时立即崩溃。调试给我一个段错误,但它没有给我导致它的特定行。我正在通过 Dev C++ 中包含的 gcc 编译器运行我的代码。 这是我的代码。任何帮助,将不胜感激。我认为我的问题是试图将一个字符串数组传递给该函数,但我无法找到关于该主题的任何我能理解的答案。

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

void sort(char *[]);

int main()
{
    char *states[4] = {0};
    states[0] = "Florida";
    states[1] = "Oregon";
    states[2] = "California";
    states[3] = "Georgia";

    sort(states);

    return 0;
}

void sort(char *ptr[])
{
    int i, j;
    char temp[20];
    for ( i = 1; i <= 4; i++ )
    {
        for ( j = 1; j <= 4; j++ )
            {
                if (strcmp(ptr[j-1], ptr[j]) > 0)
                {
                    strcpy(temp, ptr[j-1]);
                    strcpy(ptr[j-1], ptr[j]);
                    strcpy(ptr[j], temp);
                }
            }
    }

    int x;
    for ( x = 0; x < 4; x++ )
    {
        printf("%s", ptr[x]);
        printf("\n");
    }
}

最佳答案

我看到的问题:

  1. 您在 for 循环中使用了错误的索引。

    代替:

    for ( i = 1; i <= 4; i++ )
    {
        for ( j = 1; j <= 4; j++ )
    

使用:

    for ( i = 0; i < 4; i++ )   // Keep the values in the range 0 - 3.
    {
        for ( j = 0; j < 4; j++ )
  1. 您正在修改只读内存。

    当您使用时:

    states[0] = "Florida";
    

    states[0] 具有包含字符串 "Florida" 的只读地址的值。如果您在 sort 中修改该地址的值,您将进入未定义的行为领域。

您可以通过切换指针而不是复制值来解决问题。

    // Use char* for temp instead of an array
    char* temp;
    if (strcmp(ptr[j-1], ptr[j]) > 0)
    {
        temp = ptr[j-1];
        ptr[j-1] = ptr[j];
        ptr[j] = temp;
    }

附录,回应 OP 的评论

以下版本的 sort 适合我:

void sort(char *ptr[])
{
   int i, j;
   char* temp;
   for ( i = 0; i < 4; i++ )
   {
      // NOTE:
      // This is different from your version.
      // This might fix your problem.
      for ( j = i+1; j < 4; j++ )
      {
         if (strcmp(ptr[j-1], ptr[j]) > 0)
         {
            temp = ptr[j-1];
            ptr[j-1] = ptr[j];
            ptr[j] = temp;
         }
      }
   }

   for ( i = 0; i < 4; i++ )
   {
      printf("%s", ptr[i]);
      printf("\n");
   }
}

关于c - 如何将字符串数组传递给该程序中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29283029/

相关文章:

c - 对 `device_show_int()` 的调用是 Linux 内核错误吗?

javascript - 在 jQuery 中迭代数组时,每隔两个元素创建一个新列表

Java:使用流连接具有 2 个不同分隔符的 2D string[][] 数组

c - 如何在c中的两个字符串之间查找文本

c - 不确定用字符串数组初始化一维字符数组

c - 为什么这个函数序言中没有 "sub rsp"指令,为什么函数参数存储在负 rbp 偏移处?

c - 用指针修改结构体数组

c - 为什么在写入使用字符串文字初始化的 "char *s"而不是 "char s[]"时出现段错误?

c - "Program has stopped working"

Javascript - Lodash/Underscore 比较两个对象并根据它们的键更改值