1

为什么如果我myarray[x]在 main 函数中 printf 我没有得到数据(一个空行)?数组已正确填充(如果我在函数中打印,我会得到值)

这是我的代码:

int main(void)  {
    char thisxpath[300];
    char thisurl[200];
    char** myarray = NULL;
    strcpy (thisurl,"http://api.openweathermap.org/data/2.5/weather?q=Pescara&mode=xml&units=metric");
    strcpy (thisxpath,"//city/@name | //country | //weather/@value | //temperature/@value | //precipitation/@value | //humidity/@value | //speed/@*[name()='name' or name()='value']");
    xmlretrive (thisurl, thisxpath, &myarray);

    printf("%s\n", myarray[1]);

    free(myarray);
    return 0;
}

void xmlretrive(char* myurl, char* myxpath, char** myarray) {

    //code that retrieve with cURL the XML and other stuff
    //keyword contain data, that are copied into myarray

    myarray = malloc(20 * sizeof(char*));   
    for (i=0; i < nodeset->nodeNr; i++) {
    keyword = xmlNodeListGetString(doc, nodeset->nodeTab[i]->xmlChildrenNode, 1);
    myarray[i] = malloc((100) * sizeof(char));
    strcpy(myarray[i], keyword);
    // if I printf("%s\n", myarray[i]) here I can see that array is actually filled
    xmlFree(keyword);
}
4

1 回答 1

5

myarray您正在传递to的副本xmlretrive。如果要更改myarray指向 inside的内容xmlretrive,则需要将指针传递给它。即一个char***

void xmlretrive(char* myurl, char* myxpath, char*** myarray) {
    *myarray = malloc(20 * sizeof(char*));   
    for (i=0; i < nodeset->nodeNr; i++) {
        keyword = xmlNodeListGetString(doc, nodeset->nodeTab[i]->xmlChildrenNode, 1);
        (*myarray)[i] = malloc(strlen(keyword)+1);
        if ((*myarray)[i] == NULL) {
            // out of memory.  print error msg then exit
        }
        strcpy((*myarray)[i], keyword);
        xmlFree(keyword);
}

请注意,我还建议对您的malloc线路进行一些更改

  • 不应该从 malloc 中获得回报
  • 分配所需的字符串的确切长度keyword以避免缓冲区溢出的可能性strlen(keyword)>99
  • sizeof(char)保证为 1,因此您不需要将分配大小乘以它

这将解决您眼前的问题,但可能不足以让事情正常工作。其他一些需要考虑的事情:

  • main需要调用free每个分配的成员myarray以及它myarray自己
  • 你没有办法main知道myarray. 您可以将单独的length参数传递给xmlretrive或更改为在数组末尾xmlretrive添加一个元素并迭代直到您在NULLmain
  • xmlretrive应该可能为nodeset->nodeNr + 1(+1 假设您NULL向数组添加终止符)元素分配空间,而不是硬编码长度为 20
于 2013-06-17T10:34:30.620 回答