一维数组在内存中所占字节数
#include <stdio.h>
int fun2()//一维数组
{
int a[]={1,2,3};
printf("%d\n",sizeof(a));
return 0;
}
一维数组初始化时,元素的个数可以省略,但定义的时候不能省略。
设int型占4字节,则对于int a[ ]={1,2,3}; a所占字节数为4×3=12
设int型占4字节,则对于int a[10]={1,2,3}; a所占字节数为4×10=40
对数组进行定义时,方括号里的值不能是变量。
比如下列写法错误。
int i;
float score[ i ];
但对数组进行使用时,方括号内的值可以是变量但不能越界。
二维数组在内存中所占字节数
#include <stdio.h>
int fun2()//二维数组
{
int a[][3]={1,2,3,4,5,6};
//初始化时,行可以省略,列不可以
//如果在定义时,则行和列均不可省
printf("%d\n",sizeof(a));
return 0;
}
二维数组初始化时,行可以省,但列不可以。定义时行和列均不可省。
设int型占4字节,则对于int a[ ][3]={1,2,3,4,5,6}; a所占字节数为4×6=24
设int型占4字节,则对于int a[10][3]={1,2,3,4,5,6}; a所占字节数为4×30=120
字符串在内存中所占字节数
#include <stdio.h>
#include <string.h>
int fun4()//字符数组
{
char c1[] = "ABC";
char c2[] = "ABC\0DEF";
printf("c1 %d\nc2 %d\n", strlen(c1), strlen(c2));
printf("c1 %d\nc2 %d\n", sizeof(c1), sizeof(c2));
return 0;
}
因为'\0'是字符串结束的标志,所以在"ABC"和"ABC\0DEF"中,"ABC"相当于"ABC\0","ABC\0DEF"相当于"ABC\0"。这俩字符串在内存中所占字节数均为4。
gets()和puts()
#include <stdio.h>
#include <string.h>
int fun5()
{
char c1[5];
char c2[5];
printf("gets()键入字符串\n");
gets(c1);
printf("scanf()键入字符串\n");
scanf("%s", c2);
printf("puts()打印字符串\n");
puts(c1);
printf("printf()打印字符串\n");
printf("c2 %s ", c2);
printf("\n");
return 0;
}
scanf()函数使用%s读取字符串,它只能读到第一个空格前的内容。如果键入的字符串包含空格,那么只会读取到空格前的内容。
gets()函数能够从键盘读取一行字符串 ,即使有空格。
puts()函数和printf()函数相比自带换行。
strcat()、strcpy()、strcmp()、strlen()、strlwr()和strupr()
#include <stdio.h>
#include <string.h>
int fun6()
{
char c1[100];
char c2[100];
printf("gets()键入字符串\n");
gets(c1);
printf("scanf()键入字符串\n");
scanf("%s", c2);
printf("puts()打印字符串\n");
puts(c1);
printf("printf()打印字符串\n");
printf("%s\n", c2);
printf("strlen()测试字符串长度\n");
printf("c1 %d c2 %d\n",strlen(c1),strlen(c2));
printf("strcmp()比较字符串\n");
printf("%d\n",strcmp(c1,c2));
printf("\n\n\n");
//设 c1="ABC" c2="abc"
printf("strlwr()大写转小写\n");//c1=小写化的(c1)
printf("%s\n",strlwr(c1));
printf("%s %s\n",c1,c2);
//strlwr()后,c1="abc" c2="abc"
printf("strlwr()小写转大写\n");//c2=大写化的(c2)
printf("%s\n",strupr(c2));
printf("%s %s\n",c1,c2);
//strupr()后,c1="abc" c2="ABC"
printf("strcat()连接字符串\n");//相当于c1=c1+C2
printf("%s\n",strcat(c1,c2));
printf("%s %s\n",c1,c2);
//c1="abcABC" c2="ABC"
printf("strcpy()复制字符串\n");
printf("%s\n",strcpy(c1,c2));//相当于c1=c2
printf("%s %s\n",c1,c2);s
//c1="ABC" c2="ABC"
return 0;
}