为什么在尝试将指向数组的指针作为函数的参数时出现访问冲突错误?

时间:2019-02-16 09:21:07

标签: c pointers

当我尝试遍历“星期五”数组时遇到访问冲突错误。

我试图在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;
}

我只想遍历数组并求和所有元素

1 个答案:

答案 0 :(得分:1)

while(friday + i) {中,即使第一回合,测试也永远不会为假,因为星期五不是NULL指针,因此当大于1

假设您使用*(friday + i);初始化了 array1 ,可能是您想要while(friday[i] != 0) {吗?

当然还有关于星期六

的类似问题

请注意,您也可以在参数中给出数组的大小

使用{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;
}

valgrind 下:

pi@raspberrypi:/tmp $ gcc -g -pedantic -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
5

请注意,将 friSum satSum 分开以最终添加它们很复杂,仅具有唯一的 sum 更简单,这是也可能没有 sum 并直接递减 total

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