【问题标题】:passing two 2-d arrays into a function for comparison将两个二维数组传递给函数进行比较
【发布时间】:2014-01-20 15:22:55
【问题描述】:

我一直在尝试将两个数组传递给一个函数,以便我可以比较它们,但是我在传递数组和开始比较行的语法上遇到了问题。我收到诸如不兼容的指针类型传递给类型 const char 之类的错误????这是我到目前为止的代码......我在顶级排序功能中遇到了麻烦

//

#define MAXROWS    30
#define MAXCOLS   100 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char topsort( char, int, char, int);    

int main(int argc, const char * argv[])
{
    //array for all of the word's in the file
    char list[MAXROWS][MAXCOLS], line[MAXCOLS], constraint[MAXROWS][MAXCOLS];
    FILE *list_sort;
    int listcols = 0, listrows = 0, concols = 0, conrows = 0;

    //open the sequential access file and make sure its found
    list_sort = fopen("/Volumes/JENN/cpma stuff/introcompsys/list sort.txt","r");
    if(list_sort == NULL){
        printf("can't open file");
        exit(EXIT_FAILURE);
    }

    while(fgets(line, sizeof(line), list_sort) != NULL)
    {
        if(index(line, ',') == NULL){
            for(listcols =0; listcols< strlen(line)-1 ;++listcols)  {
                list[listrows][listcols] = line[listcols];
            }
            list[listrows][listcols] = '\0';
            printf("%s\n", list[listrows]);  //print each row of the list to check
            ++listrows;
        }
        else{
            for(concols =0; concols< strlen(line)-1 ;++concols)  {
                constraint[conrows][concols] = line[concols];
            }
            constraint[conrows][concols] = '\0';
            printf("%s\n", constraint[conrows]);  //print each row of the constraint to
            //check
            ++conrows;
        }

    }
}
char topsort( char s1[][MAXCOLS], int listrows, char s2[][MAXCOLS], int conrows){
char sorted[MAXROWS][MAXCOLS];

while(the constraint array is not empty){     //pseudocode
    int second = char *strchr(s2, ‘,’+ 2);  
    for(int i = 0; i < listrows ; i++){
        for(int j = 0; j < conrows; j++){
            strcspn(s2[j][second], s1[i]);
        }
    }
}

}

【问题讨论】:

  • 你的函数声明在哪里?
  • 请在问题中添加警告/错误。
  • 包括所有错误消息,包括行号。也是样本输入。
  • 您在topsort 中到底有什么问题? strlen[][]) 的语法是错误的吗?或者您的while 条件永远不会更新,并且始终为真或始终为假? strcspn 计算出一个你从不存储的长度?你在声明之前尝试调用topsort
  • 我知道 top sort 有很多问题...我两天前开始学习 C 并且需要在一周内编写一个程序,所以我只是想尽我所能找到所有帮助得到!我唯一的编程经验是 7 周的 Java;/

标签: c arrays comparison compare


【解决方案1】:

topsort 的多个问题。这是行不通的。

这是个坏主意:

char s1[][MAXCOLS]

要么指定所有维度大小,要么使用 char **。

这是错误的,有几个原因。

int length = strlen(s2[][]);

您不提供任何数组索引,您将一个 char 传递给一个接受 char * 的函数,并且您在 while 循环中使用长度并且永远不会更改它。

strlen(&s1)

这是将 char * * * 传递给期望 char * 的函数。

strcspn(s2[i], s1[i]);

将两个字符传递给一个接受一个字符和一个字符 * 的函数。而且你甚至看不到结果。

【讨论】:

  • char s1[][MAXCOLS] 是个坏主意吗?在这种情况下,从main 传递的参数(假定)具有签名list[MAXROWS][MAXCOLS]char **s1 是一个更糟糕的主意,因为数据是连续的,而不是指针数组。
  • 变量前面的 * 或 ** 是什么意思?该函数显然也没有“运行”....我不知道比较数组行内的值与仅指向它们的语法
猜你喜欢
  • 2020-11-01
相关资源
最近更新 更多