为什么如果我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);
}
Run Code Online (Sandbox Code Playgroud)
你传递的副本myarray来xmlretrive.如果要更改myarray指向内部的内容xmlretrive,则需要将指针传递给它.即achar***
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);
}
Run Code Online (Sandbox Code Playgroud)
请注意,我还建议对您的malloc行进行一些更改
keyword以避免缓冲区溢出的可能性strlen(keyword)>99sizeof(char) 保证为1,因此您不需要将分配大小乘以它这将解决您的直接问题,但可能不足以使事情正常运行.其他一些需要考虑的事项:
main需要调用free每个已分配的成员myarray以及myarray自己main知道它的长度myarray.您可以将单独的length参数传递给xmlretrive或更改xmlretrive为NULL在数组末尾添加元素并迭代直到找到它为止mainxmlretrive应该为nodeset->nodeNr + 1((假设你NULL在数组中添加一个终结符)元素而不是硬编码长度为20的空间分配空间