Chinaunix首页 | 论坛 | 博客
  • 博客访问: 471008
  • 博文数量: 98
  • 博客积分: 3265
  • 博客等级: 中校
  • 技术积分: 1227
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-23 00:29
文章分类

全部博文(98)

文章存档

2012年(6)

2011年(83)

2010年(9)

分类: C/C++

2011-04-08 20:12:41


需要的头文件

   or

函数原型

  void *memset(void *s, int ch, unsigned n);

将s所指向的某一块内存中的每个字节的内容全部设置为ch指定的ASCII值, 块的大小由第三个参数指定,这个函数通常为新申请的内存做初始化工作, 其返回值为指向S的指针。



程序例

  #include

  #include

  #include

    

int main(void)

  {

  char buffer[] = "Hello world\n";

  printf("Buffer before memset: %s\n", buffer);

  memset(buffer, '*', strlen(buffer) );

  printf("Buffer after memset: %s\n", buffer);

  return 0;

  }

  输出结果:

  Buffer before memset: Hello world

  Buffer after memset: ************




Malloc 向系统申请分配指定size个字节的内存空间。

返回类型是 void* 类型。void* 表示未确定类型的指针。void* 类型可以强制转换为任何其它类型的指针。


原型:extern void *malloc(unsigned int num_bytes);

头文件:malloc.h或者stdlib.h。

功能:分配长度为num_bytes字节的内存块

返回值:如果分配成功则返回指向被分配内存的指针,否则返回空指针NULL。


int* p;

  p = (int *) malloc (sizeof(int));//将 void* 强制转换为int * 类型变量”,分配int大小的内存


int* p = (int *) malloc ( sizeof(int) * 100 ); //分配可以放得下100个整数的内存空间。


char *ptr;

  if ((ptr = (char *)malloc(int)) == NULL)

  puts("分配内存失败");

  else

  puts("分配内存成功");


程序例

#include

#include

  int main()

  {

  int i,j;

  int *array=NULL;

  scanf("%d",&i);

  array=(int*)malloc(i*sizeof(int));

  for(j=0;j

  scanf("%d",&array[j]);

  for(j=0;j

  printf("%d\n",array[j]);

  free(array);

  array=NULL;

  return 0;

  }



=======================================

//结构指针变量作函数参数
#include
struct stu
{
int num;
char *name;
char ***;
float score;
}boy[5]=
{
{101,"Li ping",'M',45},
{102,"Zhang ping",'M',62.5},
{103,"He fang",'F',92.5},
{104,"Cheng ling",'F',87},
{105,"Wang ming",'M',58},
};

main()
{
struct stu *ps;
void ave(struct stu *ps);
ps=boy;
ave(ps);
}

void ave(struct stu *ps)
{
int c=0,i;
float ave,s=0;
for(i=0;i<5;i++,ps++)
{
s+=ps->score;
if(ps->score<60) c+=1;
}
printf("s=%f\n",s);
ave=s/5;
printf("average=%f\ncount=%d\n",ave,c);
}

测试环境:VC++6.0
输出结果:
s=345.000000
average=69.000000
count=2
Press any key to continue

阅读(1754) | 评论(0) | 转发(0) |
0

上一篇:static探究

下一篇:指针与二维数组

给主人留下些什么吧!~~