为结构数组分配空间,并学习一些C语言

时间:2016-07-04 02:20:12

标签: c arrays struct malloc

在这里尝试学习一些C.

通常我试图使用动态分配来实现这些情况。

  • 指向日期指针数组的指针
  • 指向日期数组的指针
  • 日期指针数组
  • 一系列日期
  

你能帮助我建造这些结构/检查我的想法是否合适?

#include <stdio.h>
#include <stdlib.h>
#define SIZE 2

typedef struct date {
  int year;
  short month;
  short day;
  char* wday;
} Date;

typedef struct date DatesArr[SIZE];
typedef struct date* DatesPtr;

void printDate(Date d){ printf("%d-%d-%d %s\n", d.year, d.month, d.day, d.wday); }

void printDatePtr(Date* d){ printf("%d-%d-%d %s\n", d->year, d->month, d->day, d->wday); }

int main(int argc, char *argv[]){
  Date a = *(Date*)malloc(sizeof(Date));
  a.year = 2016; a.month = 6; a.day = 12; a.wday = "sunday";
  Date b = *(Date*)malloc(sizeof(Date));
  b.year = 2016; b.month = 6; b.day = 13; b.wday = "monday";

  //Date* y = &a;  // reuse previous
  Date* y = (Date*)malloc(sizeof(Date));
  y->year = 2016; y->month = 4; y->day = 25; y->wday = "monday";
  Date* z = (Date*)malloc(sizeof(Date));
  z->year = 2016; z->month = 3; z->day = 27; z->wday = "sunday";

  // a pointer to an array of dates pointers !OK
  DatesPtr* yz = (DatesPtr *)malloc(sizeof(Date*)*SIZE);
  yz[0] = y; yz[1] = z;
  for(int i=0;i<SIZE;i++){ printDatePtr( yz[i] ); }

  // a pointer to an array of dates !OK
  DatesPtr* ab = (DatesPtr *)malloc(sizeof(Date)*SIZE);
  ab[0] = &a; ab[1] = &b;
  for(int i=0;i<SIZE;i++){ printDate( *ab[i] ); }

  // an array of dates pointers // error
  DatesArr zy[] = *(DatesArr *)malloc(sizeof(Date*)*SIZE);
  zy[0] = y; zy[1] = z;
  for(int i=0;i<SIZE;i++){ printDatePtr( zy[i] ); }

  // an array of dates // error
  DatesArr ba = *(DatesArr *)malloc(sizeof(Date)*SIZE);
  ba[0] = a; ba[1] = b;
  for(int i=0;i<SIZE;i++){ printDate( ba[i] ); }

  //free(a); // error: free only accepts a pointer to a Date
  free(y);  // runs ok
  return 0;
}

1 个答案:

答案 0 :(得分:3)

让我们来看一个:一系列日期。

代码需要一种指针$scope.ProceedToCheckout=function(checkout){ // checkout is my order information $http.post("http://nodejs-restpos.rhcloud.com",checkout).success(function(data){ console.log(data) }).error(function(data){ console.log(data) }) ,而不是Date *

Date

实施例

// bad
Date a = *(Date*)malloc(sizeof(Date));
// better
Date *a = (Date*)malloc(sizeof(Date));
// better yet - cast not needed in C
Date *a = malloc(sizeof(Date));
// better yet: allocate per the sizeof of the de-referenced type.
Date *a = malloc(sizeof *a);
// As needed, code needs 4 for a,b,y,z
Date *a = malloc(sizeof *a * 4);