[英]Why I have access violation error when trying to put a pointer to an array as parameter of a function?
當我嘗試遍歷“星期五”數組時出現訪問沖突錯誤。
我試圖在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) {
,即使第一輪測試也不會出錯,因為friday不是NULL指針,因此您可以通過*(friday + i);
訪問數組*(friday + i);
當我大於1時
可能是while(friday[i] != 0) {
假設您使用{1, 2, 0}
1、2、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\n", 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\n", 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分開以最終將它們相加是復雜的,僅具有唯一的和更簡單,也可能沒有和並直接遞減總計
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.