Day19.C提高3
一、calloc和realloc
char* arr = (char*)calloc(10, sizeof(char));
if (arr != NULL)
{
free(arr);
arr = NULL;
}
char* arr = realloc(arr, sizeof(char) * 20);
二、实现strstr
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char* myStrStr(const char* str,const char* substr)
{
const char* mystr = str;
const char* mysub = substr;
while (*mystr)
{
if (*mystr != *mysub)
{
++mystr;
continue;
}
char* temp_mystr = mystr;
char* temp_mysub = mysub;
while (*temp_mysub)
{
if (*temp_mysub != *temp_mystr)
{
break;
}
++temp_mystr;
++temp_mysub;
}
if (!*temp_mysub)
{
return mystr;
}
++mystr;
}
return NULL;
}
int main(void)
{
char* arr1 = "abcdef12564gdfpoiq";
char* arr2 = "64g";
char* result = (char*)myStrStr(arr1, arr2);
printf("%s\n", result);
return 0;
}
三、指针易错点
char* p = malloc(64);
++p;
if(p != NULL)
{
free(p);
p = NULL;
}
四、const使用
示例:
void fun_1(struct Struct_Name* Struct_Name_1){}
void fun_1(const struct Struct_Name* Struct_Name_1){}
五、二级指针练习(读文件)
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int getFileLines(FILE* file)
{
if (!file)
return -1;
char buf[1024] = { 0 };
int lines = 0;
while (!feof(file))
{
fgets(buf, 1024, file);
++lines;
}
fseek(file, 0, SEEK_SET);
return lines;
}
void readFileDate(char** EachLineP,FILE* file,int lines)
{
if (EachLineP == NULL)
return;
if (file == NULL)
return;
if (lines <= 0)
return;
int index = 0;
char buf[1024] = { 0 };
int lens = 0;
while (!feof(file))
{
fgets(buf, 1024, file);
lens = strlen(buf) + 1;
char* p = malloc(sizeof(char) * lens);
strcpy(p,buf);
EachLineP[index++] = p;
memset(buf, 0, 1024);
}
fclose(file);
file = NULL;
}
void showFileDate(char** counts, int lines)
{
for (int i = 0; i < lines; ++i)
{
printf("%d行%s", i + 1, counts[i]);
}
}
void freeFilePlace(char** counts, int lines)
{
for (int i = 0; i < lines; ++i)
{
if (counts[i] != NULL)
{
free(counts[i]);
counts[i] = NULL;
}
}
if (counts != NULL)
free(counts);
counts = NULL;
}
void test01()
{
FILE* file = fopen("test.txt", "r");
if (!file)
return -1;
int lines = getFileLines(file);
char** EachLineP = malloc(sizeof(char*) * lines);
readFileDate(EachLineP, file, lines);
showFileDate(EachLineP, lines);
freeFilePlace(EachLineP, lines);
}
int main(void)
{
test01();
return 0;
}
六、位运算
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void test01()
{
int number = 2;
printf("~number:%d\n", ~number);
}
void test02()
{
int number = 335;
if (number & 1)
{
printf("该数字为奇数");
return;
}
printf("该数字为偶数");
}
void test03()
{
int number1 = 3;
int number2 = 5;
printf("%d", number1 | number2);
}
void test04()
{
int num1 = 5;
int num2 = 9;
printf("num1:%d num1:%d\n", num1, num2);
num1 = num1 ^ num2;
num2 = num1 ^ num2;
num1 = num1 ^ num2;
printf("num1:%d num1:%d\n", num1, num2);
}
void test05()
{
int num1 = 20;
printf("num1 << 2: %d\n", num1 <<= 2);
printf("num1 << 2: %d\n", num1 >>= 1);
}
int main(void)
{
test05();
return 0;
}