【问题标题】:pointer of String throught function in C字符串指针通过C中的函数
【发布时间】:2022-08-05 21:39:42
【问题描述】:

只是试图编写这个排序函数,当我使用二维数组时它工作正常,但是当我使用指针作为数组时它不起作用!

    void sorting(char ** names, int number) { 
          for (int i = 0; i < number; i++) {//bubbleSorting 
            for (int j = 0; j < number - 1 - i; j++) {
              if (strcmp(names[j], names[j + 1]) > 0) {
                char * temp = xmalloc(number);
                strcpy(temp, names[j]);
                strcpy(names[j], names[j + 1]);
                strcpy(names[j + 1], temp);
              }
            }
          }
        }
        
        int main() {
          char * liste[4] = {
            \"cat\",
            \"pizza\",
            \"dogs\",
            \"ananas\"
          }; 
          int n = sizeof(liste) / sizeof(liste[0]);
          sorting(liste, n);
          return 0;
        }

    标签: arrays c string pointers


    【解决方案1】:
    void sorting(char ** names, int number) { 
          for (int i = 0; i < number; i++) {//bubbleSorting 
            for (int j = 0; j < number - 1 - i; j++) {
              if (strcmp(names[j], names[j + 1]) > 0) {
                char * temp = xmalloc(number);
                strcpy(temp, names[j]);
                strcpy(names[j], names[j + 1]);
                strcpy(names[j + 1], temp);
              }
            }
          }
        }
        
        int main() {
          char * liste[4] = {
            "cat",
            "pizza",
            "dogs",
            "ananas"
          }; 
          int n = sizeof(liste) / sizeof(liste[0]);
          sorting(liste, n);
          return 0;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-10
      • 1970-01-01
      • 1970-01-01
      • 2021-06-28
      • 2013-03-09
      • 1970-01-01
      • 2011-06-05
      相关资源
      最近更新 更多