int get_first(int arr[],int count)
{
int half = count / 2;
int *firstHalf = malloc(half * sizeof(int));
memcpy(firstHalf, arr, half * sizeof(int));
return firstHalf;
}
int get_second(int arr[], int count)
{
int half = count / 2;
int *secondHalf = malloc(half * sizeof(int));
memcpy(secondHalf, arr + half , half * sizeof(int));
return secondHalf;
}
int result = get_first(arr, count);
int size = sizeof(result) / sizeof(result[0]);
我正在编写一个将数组拆分为两个相等部分的函数。该函数接受一个数组和数组的大小。我通过在结果中存储数组的前半部分并打印其长度来测试该功能。但是当我构建函数时,
int size = sizeof(result) / sizeof(result[0]);
给出一个错误,指出“错误:下标值既不是数组也不是指针”
是否因为我的函数无法将数组的前半部分传递给结果?还是存储数组的方式错误?如果是这样,我如何拆分阵列,有人可以帮助我修复它吗?提前致谢。
最佳答案
我可以看到两个问题:
在函数int get_first(int arr[],int count)
和int get_second(int arr[], int count)
中,您将返回int指针,但函数的返回类型为int。
result被声明为int,但是您像result [0]一样访问它。
从上面的点1可以明显看出对1的校正。
更正2:
代替:
int result = get_first(arr, count);
您应该写:
int *result = get_first(arr, count);
希望这可以帮助。
关于c - 错误:下标值既不是数组也不是指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42048862/