为什么在尝试将指向数组的指针作为函数的参数时出现访问冲突错误?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了为什么在尝试将指向数组的指针作为函数的参数时出现访问冲突错误?相关的知识,希望对你有一定的参考价值。
当我试图遍历'周五'数组时,我遇到了访问冲突错误。
我试图在while循环之前检查空指针,但仍然......
int lostSheep(const int *friday, const int* saturday, int total)
{
int friSum = 0;
int satSum = 0;
int i = 0;
while(friday + i) {
friSum += *(friday + i);
i++;
}
i = 0;
while(saturday + i) {
satSum += *(saturday + i);
i++;
}
int sum = satSum + friSum;
return total - sum;
}
int main() {
int array1[] = { 1, 2 };
int array2[] = { 3, 4 };
printf("%d", lostSheep(array1, array2, 15));
return 0;
}
我只想迭代数组并总结所有元素
答案
在while(friday + i) {
中,即使是第一个转弯,测试也永远不会是假的,因为周五不是NULL指针,因此当我大于1时你可以访问数组中的*(friday + i);
可能你想要while(friday[i] != 0) {
假设你用{1, 2, 0}
初始化array1?
当然,星期六有一个类似的问题
请注意,您还可以在参数中指定数组的大小
使用friday[i]
而不是*(friday + i)
更具可读性
第一种可能是添加空值来标记数组的结尾:
#include <stdio.h>
int lostSheep(const int *friday, const int* saturday, int total)
{
int friSum = 0;
int satSum = 0;
int i = 0;
while(friday[i]) {
friSum += friday[i];
i++;
}
i = 0;
while(saturday[i]) {
satSum += saturday[i];
i++;
}
int sum = satSum + friSum;
return total - sum;
}
int main() {
int array1[] = { 1, 2, 0 };
int array2[] = { 3, 4, 0 };
printf("%d
", lostSheep(array1, array2, 15));
return 0;
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -g -pedantic -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
5
给出数组大小的第二种可能性:
#include <stdio.h>
int lostSheep(const int *friday, size_t sz1,
const int* saturday, size_t sz2,
int total)
{
int friSum = 0;
int satSum = 0;
size_t i;
for (i = 0; i < sz1; ++i) {
friSum += friday[i];
}
for (i = 0; i < sz2; ++i) {
satSum += saturday[i];
}
int sum = satSum + friSum;
return total - sum;
}
int main() {
int array1[] = { 1, 2 };
int array2[] = { 3, 4 };
printf("%d
", lostSheep(array1, sizeof(array1)/sizeof(int),
array2, sizeof(array2)/sizeof(int),
15));
return 0;
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -g -pedantic -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
5
在valgrind下:
pi@raspberrypi:/tmp $ valgrind ./a.out
==3996== Memcheck, a memory error detector
==3996== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==3996== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==3996== Command: ./a.out
==3996==
5
==3996==
==3996== HEAP SUMMARY:
==3996== in use at exit: 0 bytes in 0 blocks
==3996== total heap usage: 1 allocs, 1 frees, 1,024 bytes allocated
==3996==
==3996== All heap blocks were freed -- no leaks are possible
==3996==
==3996== For counts of detected and suppressed errors, rerun with: -v
==3996== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)
p
注意将friSum和satSum分开以最后添加它们很复杂,只要有一个唯一的总和就更简单了,也有可能没有总和和直接decr总数
int lostSheep(const int *friday, size_t sz1,
const int* saturday, size_t sz2,
int total)
{
size_t i;
for (i = 0; i < sz1; ++i) {
total -= friday[i];
}
for (i = 0; i < sz2; ++i) {
total -= saturday[i];
}
return total;
}
以上是关于为什么在尝试将指向数组的指针作为函数的参数时出现访问冲突错误?的主要内容,如果未能解决你的问题,请参考以下文章