标签:C语言
malloc函数//动态分配内存,输入5个数据,并把低于60的值打印出来
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr = (int *)malloc(5 * sizeof(int));//分配内存
for (int i = 0; i < 5; i++)
{
scanf_s("%d", &ptr[i]);//输入数据
}
int min = 60;
for (int i = 0; i < 5; i++)
{
if (min > *(ptr + i))
printf("%5d", *(ptr + i));//打印出低于60的值
}
free(ptr);
system("pause");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *str;
/* 一开始的内存分配 */
str = (char *)malloc(15);
strcpy(str, "Hello World!");
printf("String = %s\n", str);
/* 重新分配内存 */
str = (char *)realloc(str, 25);
strcat(str, ", C");
printf("String = %s\n", str);
free(str);
system("pause");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
int i;
int *ptr;
printf("元素个数为:");
scanf("%d", &num);
ptr = (int*)calloc(num, sizeof(int));
printf("输入 %d 个数字:\n", num);
for (i = 0; i < num; i++)
{
scanf("%d", &ptr[i]);
}
printf("输入的数字为:");
for (i = 0; i < num; i++) {
printf("%d ", ptr[i]);
}
printf("\n");
system("pause");
return 0;
}
标签:C语言
原文地址:http://blog.51cto.com/13473568/2122129