动态分配内存,字符串操作
动态内存分配
在说动态内存分配之前先说下 静态内存分配
void main(){
int a
[1024*1024*10];
}
堆内存 栈内存
下面代码 作用 每隔一秒申请40M 内存 看任务管理器 可以看到 别搞死机了,可以把free注释 打开 不过就看不到效果了
void heapFun(){
int* p
= malloc(1024 * 1024 * 10 * sizeof(int));
}
void main(){
while (1){
Sleep(1000);
stackFun();
}
getchar();
}
写个例子01 : 输入一个数 随机生成这个数的长度的数组 并打印
void main(){
int len
;
printf("输入数组的长度:");
scanf("%d",&len
);
int* p
= malloc(len
* sizeof(int));
int i
= 0;
for (; i
< len
- 1; i
++){
p
[i
] = rand() % 100;
printf("%d,%#x\n", p
[i
], &p
[i
]);
}
free(p
);
system("pause");
}
例子: 输入数组长度,生成数组,再次输入新的数组长度,两个数组合并,再重新生成.使用 realloc 函数 重新分配内存
void main(){
int len
;
printf("第一次输入数组的长度:");
scanf("%d", &len
);
int* p
= NULL;
p
= (int*)calloc(len
, sizeof(int));
int i
= 0;
for (; i
< len
; i
++){
p
[i
] = rand() % 100;
printf("%d,%#x\n", p
[i
], &p
[i
]);
}
int addLen
;
printf("输入数组增加的长度:");
scanf("%d", &addLen
);
int* p2
= (int*)realloc(p
, sizeof(int)* (len
+ addLen
));
if (p2
== NULL){
printf("重新分配失败");
}
i
= 0;
printf("--------------------------\n");
for (; i
< len
+ addLen
; i
++){
p2
[i
] = rand() % 200;
printf("%d,%#x\n", p2
[i
], &p2
[i
]);
}
if (p2
!= NULL){
free(p2
);
p2
= NULL;
}
system("pause");
}
在这里我遇到一个深坑
if (p2
!= NULL){
free(p2
);
p2
= NULL;
}
一开始我把两个指针都释放了 结果报错 , 原因: 二次释放了 因为p 和p2的地址是相同的,打印一下就知道了.
字符串操作 字符串例子
字符串例子01 初始化
void main(){
char ch1
[10] = { 'c', 'h', 'i', 'n', 'a','\0' };
printf("%s\n", ch1
);
printf("%x#\n", ch1
);
char str
[10] = "china";
printf("%s\n", str
);
printf("%x#\n", str
);
str
[0] = 's';
printf("修改后: %s\n", str
);
system("pause");
}
效果图
字符串例子02 指针初始化 以及操作
void main(){
char *str
= "how are you ?";
printf("%s\n", str
);
printf("%x#\n", str
);
str
+= 3;
while (*str
)
{
printf("%c", *str
);
str
++;
}
printf("\n字符串截取完成\n");
getchar();
}
下面是c语音 用于操作字符串的函数 以及网站速查
//strcat字符串拼接函数
//在线API文档:
//http://www.kuqin.com/clib/string/strcpy.html
/*
void main(void){
char dest[50];
char *a = "china";
char *b = " is powerful!";
strcpy(dest, a);
strcat(dest, b);
printf("%s\n", dest);
system("pause");
}
*/
//strchr在一个串中查找给定字符的第一个匹配之处
/*
void main(void){
char *str = "I want go to USA!";
printf("%#x\n", str);
//U元素的指针
//str+3
char* p = strchr(str, 'w');
if (p){
printf("索引位置:%d\n", p - str);
}
else{
printf("没有找到");
}
system("pause");
}
*/
//strstr 从字符串haystack中寻找needle第一次出现的位置
void main(void){
char *haystack = "I want go to USA!";
char *needle = "to";
//U元素的指针
char* p = strstr(haystack, needle);
if (p){
printf("索引位置:%d\n", p - haystack);
}
else{
printf("没有找到");
}
system("pause");
}