龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > C/C++开发 >

C语言指针的长度和类型深入分析(2)

时间:2014-09-11 11:18来源:网络整理 作者:网络 点击:
分享到:
测试代码: #include stdio.h#include stdlib.h#include unistd.h#include stdint.h#include string.h#include assert.h#define ID_STR_LEN 12#define NAME_STR_LEN 10typedef struct student{ char id[ID_STR_

测试代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <string.h>
#include <assert.h>

#define ID_STR_LEN  12
#define NAME_STR_LEN 10

typedef struct student
{
  char id[ID_STR_LEN];
  char name[NAME_STR_LEN];
  uint8_t age;
}student;

student * create_student()
{
  student *stu = (student *)malloc(sizeof(student));
  if (stu == NULL)
  return NULL;
  memset(stu, 0, sizeof(student));
  return stu;
}

void *free_student(student *stu)
{
  if (stu)
  free(stu);
  return 0;
}

static void init_student(student * stu)
{
  assert(stu);
  const char *id = "2013112210";
  const char *name = "Anker";
  uint8_t age = 21;
  memcpy(stu->id, id, strlen(id));
  memcpy(stu->name, name, strlen(name));
  stu->age = age;
}

static int handle_student(intptr_t handle)
{
  if (handle == 0)
  {
  return -1;
  }
  student *stu = (student*)handle;
  printf("id: %s\n", stu->id);
  printf("name: %s\n", stu->name);
  printf("age: %u\n", stu->age);
  return 0;
}

int main(void)
{
  student *stu;
  stu = create_student();
  init_student(stu);
  //将指针转换为intptr_t类型
  intptr_t handle = (intptr_t)stu;
  handle_student(handle);
  free_student(stu);
  return 0;
}

希望本文所述实例对大家C程序设计的学习有所帮助。

精彩图集

赞助商链接