我在处理C语言中的数组时遇到了一个问题,你看,这是我的代码的一部分,它基本上读取了一个文件,并组织了葡萄牙第三级行政区划的地块顶点的坐标-我们称之为Freguesias。在练习的这一部分,我需要写出文件中出现的所有2级管理部门的名称- Concelhos (它已经在我的数组地图制图的代码中很好地定义了,这不是问题)。
我想做一个显示Concelhos出现在文件中的函数,我想用这个子函数和函数来写,这样我以后就可以更改一些东西,但是由于某种原因,它不打印"command_list_concelhos“中的字符串,它只打印空字符串。我不知道为什么会发生这种情况,特别是如果我在"read_string_concelhos“中的for内部和外部执行一个printf,那么它就是正确的。
很抱歉,如果这个问题被错误地解释了,太大了或者只是我遗漏了一个小细节,但我没有更好的方法来解释它……
#define MAX_STRING 256
#define MAX_NAMES  50
typedef char String[MAX_STRING];
typedef struct {
    String list[MAX_NAMES];
    int n_strings;
}   StringList;
int read_string_concelhos(StringList s ,Cartography cartography, int n)
{
    int i, j=1;
    strcpy (s.list[j-1], cartography[0].identification.concelho);
    for ( i = 0 ; i < n ; i++){
        if ( strcmp(cartography[i].identification.concelho, s.list[j-1]) != 0){
            strcpy(s.list[j] , cartography[i].identification.concelho);
            j++;
        }
    }
    return j; // n_strings
}
void command_list_concelhos(Cartography cartography, int n)
{
    StringList s;
    s.n_strings = read_string_concelhos(s, cartography, n);
    int i;
    for(i = 0; i < s.n_strings; i++ )
    {
        printf("\n", s.list[i]);
    }
}发布于 2018-12-10 23:04:55
int read_string_concelhos(StringList s ,Cartography cartography, int n)
应更改为
int read_string_concelhos(StringList* s ,Cartography cartography, int n)
在函数int read_string_concelhos(StringList* s ,Cartography cartography, int n) { ... }中,所有的s.list[...]都应该更改为s->list[...]。通过这种方式,参数s是一个指针,因此strcmp将粘贴到command_list_concelhos中声明的s,这是所需的行为。
https://stackoverflow.com/questions/53688779
复制相似问题