【问题标题】:Passing an array of strings from a function to main function (C code)将字符串数组从函数传递到主函数(C 代码)
【发布时间】:2013-06-16 15:28:51
【问题描述】:

我的 C xmlretrive 函数(thisurl,thisxpath)使用 cURL 从给定 URL 检索 XML,并将获得的 chunk.memory 发送到 libxml2 解析器,该解析器使用 xpath 探索所有节点并匹配 thisxpath 表达式(基本上从某些节点属性返回一些文本) . 这很困难(我是一个初学者程序员),但是经过几天的工作,在这个论坛中进行了一些搜索以及堆栈社区的一些帮助,我让我的代码可以工作。太棒了.. 但是.. 但现在我正面临我的最后一个问题(我真诚地猜想这会容易得多)。

我在 xmlretrive 中有我的数据,好的,但是如何将这些信息传递回主函数? 用结果填充字符串数组,然后从 main 访问该数组(最后释放内存)是一种好的行为吗?我怎样才能做到这一点?还是有任何其他“标准/安全”程序?我读过不可能“返回”一个数组。一些帮助将不胜感激,因为实际上我只能在屏幕上打印结果(当然还有在 xmlretrive 函数内部):\

最好, 乔瓦尼。

int main(void)  {
char thisxpath[200];
char thisurl[200];
strcpy (thisurl,"http://api.openweathermap.org/data/2.5/forecast/daily?q=Pescara&mode=xml&units=metric&cnt=3");
strcpy (thisxpath,"//time/@day | //symbol/@name | //windSpeed/@name | //temperature/@*[name()='day' or name()='min']");
xmlretrive (thisurl, thisxpath);
return 0;
}

void xmlretrive(char* myurl, char* myxpath) {
//code, code, a lot of code
for (i=0; i < nodeset->nodeNr; i++) {
    keyword = xmlNodeListGetString(doc, nodeset->nodeTab[i]->xmlChildrenNode, 1);

    printf("keyword: %s\n", keyword);

    // Need to get keyword values back to main//        



xmlFree(keyword);}
//code
}

【问题讨论】:

标签: c function return


【解决方案1】:

将keywords 复制到一个链表并返回给main。这样您就可以在 main 中迭代和打印它们。

此外,您不必事先知道关键字列表的大小。确保将关键字字符串 libxml 返回复制到链表节点并 xmlFree 释放它以避免内存管理问题。

【讨论】:

    【解决方案2】:

    使用指针。像这样:

        int main(void)  {
    char thisxpath[200];
    char thisurl[200];
    strcpy (thisurl,"http://api.openweathermap.org/data/2.5/forecast/daily?q=Pescara&mode=xml&units=metric&cnt=3");
    strcpy (thisxpath,"//time/@day | //symbol/@name | //windSpeed/@name | //temperature/@*    [name()='day' or name()='min']");
    char** plop = NULL;
    xmlretrive (thisurl, thisxpath, &plop);
    return 0;
    }
    
    void xmlretrive(char* myurl, char* myxpath, char*** plop) {
    //code, code, a lot of code
    for (i=0; i < nodeset->nodeNr; i++) {
        keyword = xmlNodeListGetString(doc, nodeset->nodeTab[i]->xmlChildrenNode, 1);
    
        printf("keyword: %s\n", keyword);  
        /* Malloc plop and initialize it as you want*/
    
    
    xmlFree(keyword);}
    //code
    }
    

    它有点难看,但它比全局变量好得多。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-24
      • 2015-09-09
      • 1970-01-01
      • 2017-01-07
      • 2013-06-27
      • 1970-01-01
      • 2016-12-08
      相关资源
      最近更新 更多