- 论坛徽章:
- 0
|
这样修改了行不?还有什么地方可以改进的吗?
比如指针的释放???
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <setjmp.h>
- int current = 0;
- int total = 10;
- char* dynamic = NULL;
- static jmp_buf jmp;
- static void add(char c);
- int main(void)
- {
- int i;
- char c = 'a';
- for(i = 0; i < 26; i++){
- add(c);
- c++;
- }
- if(setjmp(jmp) != 0){
- printf("memory distribution error\n");
- exit(1);
- }
- for(i = 0; i < 26; i++){
- printf("%c\t", dynamic[i]);
- }
- printf("\n");
- exit(0);
- }
- static void add(char c)
- {
- char* temp = NULL;
- if(dynamic == NULL){
- temp = (char* )malloc(total);
- if(temp == NULL){
- longjmp(jmp, 1);
- }
- else{
- dynamic = temp;
- }
- }
- if(current == total - 1){
- total *= 2;
- temp = (char* )realloc(dynamic, total);
- if(temp == NULL){
- longjmp(jmp, 2);
- }
- else{
- dynamic = temp;
- }
- }
- else{
- dynamic[current] = c;
- current++;
- }
- }
复制代码 |
|