【发布时间】:2021-08-16 13:25:44
【问题描述】:
所以,一个简单的搜索函数应该返回一个指向数组的指针,该数组的元素索引与 x 匹配,并与另一个指针 - *count 保持计数。根据编译器的不同,当我调用此函数或有关 realloc 将 void 转换为 int 的错误时,它会停止执行,其中一个也给了我一个分段错误......最令人困惑的部分是我在其他项目上有非常相似的函数并且它有效直到今天(我有截图证明它确实如此)并且没有被触及。
int *search(int arr[], int n, int x, int *count)
{
int arrsize = 0;
int *pointarr = malloc(sizeof(int));
for (int i = 0; i < n -1; i++)
{
if (arr[i] == x)
{
arrsize++;
pointarr = realloc(pointarr, sizeof(int) * arrsize);
pointarr[arrsize - 1] = i;
}
}
*count = arrsize;
return pointarr;
}
我知道我的指针和内存分配从来都不是很好,但它确实有效......我迷路了。
int main()
{
int x, n;
int *tab; // it's later filled no problem as other, simpler function calls it with no problems
int *tabindex;
int *count = 0; //I tried with both =0 and without
//////
tabindex = search(tab, n, x, count); //I tired with all stuff like &count *count etc etc if that's the problem but I don't think so
for (int j = 0; j < *count; j++)
printf("%d ", tabindex[j]);
【问题讨论】:
-
int *pointarr = malloc(sizeof(int));-->int *pointarr = NULL; -
"converting void to int" 嗯...确定这是一个正确的报价?
-
i < n -1嗯...为什么-1? -
严格来说,您不应该在检查 NULL 之前将
realloc返回的值保存在pointarr中。在任何情况下,您都应该在pointarr[arrsize - 1] = i;之前检查NULL。也就是说,我认为这不是真正的问题 -
这只是检查我是否没有尝试访问我不应该访问的东西的遗物,它现在不会影响代码,因为它在我的电脑上没有 -1。
标签: c memory segmentation-fault