В while(friday + i) {
тест никогда не ложен даже в первый ход, потому что пятница не является указателем NULL, поэтому вы получаете доступ из массива, делая *(friday + i);
, когда i больше 1
Может быть, вы хотели while(friday[i] != 0) {
предположим, что вы инициализировали array1 с {1, 2, 0}
?
Конечно, есть аналогичная проблема, связанная с суббота
Обратите внимание, что вы также можете указать размер массива в параметре
. Он удобнее читать 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 отделены, чтобы, наконец, добавить их, сложно, просто иметь уникальную сумму проще, это такжеo возможно не иметь sum и непосредственно decr total
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;
}