今天复习了一下指针与数组;自学了有关结构体的一些内容。
指针数组:是一个数组里面元素全是指针即地址,所以改变里面的元素要想操作指针一样,指针数组元素用之前应当进行初始化,不然编译时容易出现段错误;打印数组指针就是打印元素当前指向的地址内的内容。
例如: char *str[10] = {"i", "am","from", "shanghai"};
int i;
for(i = 0; i < 5; i++)
printf("%s",str[i]);
如利用指针数组将数组内的字符串进行倒序输出:把ptr[i]像指针一样操作,但是和指针不同的是指针数组是一群指针,而我们平时用的指针只有一个,ptr[i] = str[3-i];这样赋值之后只会移动输出最后指向的地址里的内容,而不能输出一句话。
#include<stdio.h>
#include<string.h>
int main()
{
char *str[20] = {"i","am","from","shanghai"};
char *ptr[20] = {0};
int i, count = 0;
for(i = 0; i < 4; i++)
{
ptr[i] = str[3-i];
printf("%s\t",ptr[i]);
}
return 0;
}
还有要把一段字符串中有效的帧给提取出来:要提取需要用到检测字符串是否符合条件,先比较head调用strcmp();来对比如果满足条件在比较tail如果都满足直接把指针指向head这个地址然后打印;
int main()
{
char *str =(char*) malloc(sizeof(char)*64);
printf("please input:\n");
scanf("%s",str);
printf("%s\n",str);
int len, i, j;
len = strlen(str);
printf("%d\n",len);
for(i = 0; i < len-3; i++)
{
if(strncmp(str + i, "head",4) == 0)
{
for(j = i; j < len -3; j++)
if(strncmp(str+j,"tail",4)==0)
{
printf("%s\n",str+i);
break;
}
}
else
continue;
}
return 0;
}
最后自学了一点结构体知识:定义一个结构体的格式如下:
struct person
{
int aa;
char dd[20];
}
struct person stu1;
结构体允许至少15级的嵌套,调用时或者要修改其中某一项内容时:要用.来链接如:person.aa = 1;这样进行修改;
结构体数组应用的是最多的 ;定义时struct 结构体名 结构体数组名 例如struct student st[10];它有十个元素,每个元素都是struct student 结构体,占用内存 10*sizeof(struct student)。