错误:二进制 + 的操作数无效(具有 'int *' 和"int *")|


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *flot = fopen("input.txt","r");
int *tab [2001];
char k[255];
int i=0;
while (fscanf(flot, "%s", k) != EOF)
{
int b = atoi(k);
tab[i]=b;
i++;
}
tab[2001]=0;
int nb = 0;
for(int i=0;i<1998;i+=3)
{
int sum1 = tab[i]+tab[i+1]+tab[i+2];
int sum2 = tab[i+3]+tab[i+4]+tab[i+5];
if(sum2>sum1)
nb++;
}
printf("%i", nb);
}

错误来自两个总和我不记得C禁止这个

C一直禁止指针的加法(但不禁止减法(。使用指针算术,您可以添加和减去指针和整数

int *ip = malloc(2 * sizeof *ip);
printf("where ip points: %pn", (void *)(ip + 0));
printf("where ip+1 points: %pn", (void *)(ip + 1));
// points one past the last elment in ip's allocation.
// you can point here, but not dereference the pointer.
int *jp = ip + 2;
printf("where jp points: %pn", (void *)jp);
printf("where jp-1 points: %pn", (void *)(jp - 1));

(在该代码中转换为void *只是为了printf的利益,其中%p需要void指针(。

您还可以从另一个指针中减去一个指针,以获得它们之间有多少底层类型的元素

printf("dist from ip to jp: %tdn", jp - ip);
printf("dist from jp to ip: %tdn", ip - jp);

但只有当它们指向同一个分配的块时,才能保证这一点(我忘记了技术术语,但只有当它是同一个类似数组的分配的一部分时,无论是在堆上、全局上还是在堆栈上,才能保证它会起作用(。

// This may or may not work (so don't do it)
int *kp = malloc(5 * sizeof *kp);
printf("dist from ip to kp: %tdn", kp - ip);
printf("dist from kp to ip: %tdn", ip - kp);

您从未被允许添加指针。这甚至不应该编译。

printf("this doesn't make sense! %pn", (void *)(ip + jp));

当您添加或减去整数时,只有当您没有超出分配的块,或者将一点指向块中最后一个元素之后,才能保证它有效。因此,如果你分配两个整数,就像上面的ip一样,你可以指向第一个地址ip == ip + 0和下一个整数ip + 1,你可以取消引用它们。您也可以将一个地址指向两个块之后的ip + 2(就像我们在上面对jp所做的那样(,但您不能取消引用该地址。你可能会也可能不会在这个范围之外进行寻址,但标准并不能保证这种行为。

// You are strictly speaking not allowed to point
// before your allocation or more than one past.
printf("where ip-1 points: %pn", (void *)(ip - 1));
printf("where ip+3 points: %pn", (void *)(ip + 3));

在你的代码中,你可能不想要

int *tab [2001];

是一个指针数组,而是

int tab [2001];

整数数组。毕竟,您稍后会将数组中的元素视为整数。

int b = atoi(k);
tab[i]=b;
…
tab[2001]=0; // although this could be a NULL assignment
…
int sum1 = tab[i]+tab[i+1]+tab[i+2];        

最新更新