编写一个函数来计算c ctruct中的elemets数

时间:2015-05-03 08:03:16

标签: c arrays pointers struct

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

我有这些错误:

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);

}

1 个答案:

答案 0 :(得分:2)

#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
}