如何解决具有realloc的函数中具有数组的C指针
| 你好 我正在慢慢转向指针和间接访问,但是仍然遇到一些麻烦。 在我的main
函数中,我使用malloc
创建一个结构体(计算机)数组
int arraySize = 0;//This may be the first issue
Computer *ptrComputer = NULL;
ptrComputer = (Computer*) malloc(sizeof(Computer) * arraySize);
然后,我将指针传递给一个函数,该函数从文件中读取数据并读入数组
arraySize = readFileToArray(&ptrComputer,arraySize);
int readFileToArray(Computer **compArray,int arraySize){
Computer newComp;
int foundARecord = 0;
/*File stuff*/
arraySize = extendArrays(compArray,arraySize,no_elements);
/*Use fscanf to read file data into the newComputer variable*/
printf(\"g %i\\n\",arraySize);
*compArray[arraySize - 1] = newComp;//set the newly created part of the array to newComputer
return arraySize;
}
int extendArrays(Computer **compArray,int arraySize){
arraySize++;
//Resize the computer array
*compArray = (Computer*)realloc(*compArray,(sizeof(Computer)*(arraySize + 1)));
return arraySize;
}
现在据我了解,我正在将ptrComputer的地址传递给readFileToArray()
函数。然后它将相同的地址传递给“ 5”函数,该函数将调整其大小。然后,我试图将newComp分配给compArray指向的内存中的位置。只要我尝试写入索引0,此方法就起作用,但其他任何原因都会导致xcode抛出exc_bad_access错误。这一切都非常令人困惑,任何对此有经验的人都可以看到我要去哪里了吗?在我将实际的指针传递给readFile
函数之前,它一直在工作,但是只工作了一次(认为我正在重新分配该指针的副本)
任何帮助将不胜感激
谢谢
解决方法
代替这个:
*compArray[arraySize - 1] = newComp;//set the newly created part of the array to newComputer
尝试这个:
(*compArray)[arraySize - 1] = newComp;//set the newly created part of the array to newComputer
这样,您可以在下标之前显式取消对compArray的引用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。