C和指针 第十一章 习题
1编写calloc,内部使用malloc函数获取内存
#include <stdio.h> #include <stdlib.h> void *myAlloc(unsigned long int length, unsigned long int typeSize) { int *ptr; int index = 0; int totalLen = length * typeSize; if(length >= 0 && typeSize >= 0){
//返回后需要类型转换一下,不可以对void *类型直接取值。 ptr = (int*)malloc(totalLen); if(ptr != NULL){ for(index = 0; index < totalLen; index++){ *(ptr + index) = 0; } return ptr; } return NULL; } return NULL; } int main() { int *ptr = myAlloc(10, sizeof(int)); int index; for(index = 0; index < 10; index++){ printf("%d\t", *(ptr + index)); } }
运行
2.编写函数从标准输入读取一列整数,把这些值存储于一个动态分配的数组中,并返回数组,函数通过EOF判断输入结束,数组第一个元素表示数组长度。
#include <stdio.h> #include <stdlib.h> int *getInputToArray() { int *array; int count = 0; int num; array = malloc(1); array[0] = count; while(scanf("%d", &num) != EOF){ count++; array = realloc(array, (count + 1)* sizeof(int)); array[count] = num; array[0] = count; } return array; } int main() { int *arr = getInputToArray(); printf("%d\n", arr[0]); return 0; }
运行输入ctrl+D结束符EOF
3.编写函数从标注输入中读取字符串,然后把字符串复制到动态分配的内存中,并返回该字符串的拷贝,不应该对输入长度做限制。
#include <stdio.h> #include <string.h> #include <stdlib.h> char *getInputStringy() { char *str = malloc(1); char *tmp; //加上末尾的'\0',初始的length应该为1 int length = 1; char ch; while((ch = getchar()) != EOF){ length++; tmp = realloc(str, length * sizeof(char)); if(tmp != NULL){ //保存输入的字符 strcpy(tmp, str); tmp[length - 2] = ch; tmp[length - 1] = '\0'; }else{ return NULL; } str = tmp; } return str; } int main() { char *str = getInputStringy(); printf("%s", str); return 0; }
运行:ctrl+D停止输入
4.编写一个链表
#include <stdio.h> #include <stdlib.h> typedef struct node { //指向下一个结构体的指针 struct node *next; int value; } LinkList; int main() { LinkList third = {NULL, 3}; LinkList second = {&third, 2}; LinkList first = {&second, 1}; struct node *ptr = &first;; while(ptr != NULL){ printf("%d\t", ptr -> value); ptr = ptr -> next; } return 0; }
运行: