gpt4 book ai didi

c - 编写一个函数来计算 c 结构中的元素数量

转载 作者:行者123 更新时间:2023-11-30 20:13:30 24 4
gpt4 key购买 nike

您好,我正在编写一个程序来计算结构中当前元素的数量,但我遇到以下错误,并且不知道如何修复它们,提前感谢

我有这些错误:

structponters.c:4:30: error: array type has incomplete element type
void sizeStruct(struct point coordinates[]);
^
structponters.c:4:24: warning: ‘struct point’ declared inside parameter list
void sizeStruct(struct point coordinates[]);
^
structponters.c:4:24: warning: its scope is only this definition or

declaration, which is probably not what you want
structponters.c: In function ‘main’:

structponters.c:23:19: warning: assignment makes pointer from integer without a cast
sizeCoordinates = sizeof coordinates / sizeof coordinates[0];
^
structponters.c:28:14: error: type of formal parameter 1 is incomplete
sizeStruct(coordinates);
^
structponters.c: In function ‘sizeStruct’:
structponters.c:35:26: warning: comparison between pointer and integer
while(coordinates[i].x != NULL)
^
structponters.c:28: confused by earlier errors, bailing out

这是代码:

#include <stdio.h>
#include <stdlib.h>

void sizeStruct(struct point coordinates[]);

struct point{
int x;
int y;
};

main(){

struct point *pp = malloc(sizeof(struct point));
pp->x = 4;
pp->y = 7;


struct point coordinates[] = {{3,5}, {7,9}, {9,12}, {15, 19}};


int *sizeCoordinates = malloc(sizeof(int));

sizeCoordinates = sizeof coordinates / sizeof coordinates[0];
printf("%d, %d\n", pp->x, pp->y);

printf("size of coordinates is %d \n", sizeCoordinates);

sizeStruct(coordinates);


}

void sizeStruct(struct point coordinates[]){
int i =0;
while(coordinates[i].x != NULL)
i = i +1;
printf("number of elemets in coordinates is: %d\n", i);

}

最佳答案

#include <stdio.h>
#include <stdlib.h>

//Required before `sizeStruct` because sizeStruct use the `struct point`
struct point{
int x;
int y;
};

void sizeStruct(struct point coordinates[]);

int main(void){
struct point *pp = malloc(sizeof(struct point));
pp->x = 4;
pp->y = 7;

struct point coordinates[] = {{3,5}, {7,9}, {9,12}, {15, 19}, { 0, 0}};//{0,0} is sentinel

int sizeCoordinates;//no need malloc, just use int

sizeCoordinates = sizeof coordinates / sizeof coordinates[0];

printf("%d, %d\n", pp->x, pp->y);

printf("size of coordinates is %d \n", sizeCoordinates);

sizeStruct(coordinates);

free(pp);

return 0;
}

void sizeStruct(struct point coordinates[]){
int i =0;
while(coordinates[i].x != 0 && coordinates[i].y != 0)//!= NULL : Comparison of the int and pointer type incorrect
i = i + 1;
printf("number of elemets in coordinates is: %d\n", i);//The number of valid data
}

关于c - 编写一个函数来计算 c 结构中的元素数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30011563/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com