当前位置:网站首页>C language - character array - string array - '\0' -sizeof-strlen() -printf()
C language - character array - string array - '\0' -sizeof-strlen() -printf()
2022-07-29 04:00:00 【Xiaowa 123】
1. Character array and string array
Array of strings : String array is a special expression of character array , Its essence is an array of characters .
Such as char mychar[]="hello", The string array also stores characters one by one , For string arrays , Stored in the system as :'h' ,'e' ,' l', 'l', 'o', '\0' , among ,'\0' As a sign of the end of a string , Last end identifier ‘\0’ It's automatically added by the system .
Such as char mychar[5]="hello", Five storage spaces are allocated for initialization , The system has no space to add \0, In memory, it is according to 'h' ,'e' ,' l', 'l', 'o' Stored .
2. About strlen() Function and sizeof Use on character arrays and string arrays
Just make two points clear :
strlen() Is the function , Its parameters are pointers , When string array and character array name are used as parameters , Array names degenerate to pointers , No longer a pointer constant .strlen() The value of is indexed to \0 The number of characters before .
sizeof Not a function , Completely according to the character array / The number and size of bytes occupied by string array when stored in memory .
printf() Function and strlen() The function is the same , Are indexed to \0 Output the result as an end sign .
3. For character arrays / Array of strings , Why use strlen() Sometimes the result is wrong , Whether to consider the actual size \0 Well ? See note below , Several different initialization situations are listed . The key is to see , How arrays are stored in memory .
#include <stdio.h>
#include <string.h>
int main(void)
{
// '\0' Is the character ( character string ) Flag of the end of the array .
//=============================== A character array =======================================
char mychar1[] = { 'c', ' ', 'b', 'd', 'd', '\0', '\0' };//strlen The result is indexed to \0 Number of preceding characters ,strlen It's a function , Its parameter is the pointer of array conversion .
printf("sizeof mychar1 is %d\n", sizeof(mychar1));// sizeof mychar1 is 7
printf("strlen of mychar1 is %d\n", strlen(mychar1)); // strlen of mychar1 is 5
printf("mychar1 is %s\n", mychar1);//c bdd
char mychar2[] = { 'c', ' ', 'b', 'd'};// This kind of data has no definite size ,mychar2[], Nor does it give \0 End mark , use strlen() You will get wrong data , Out of commission strlen().
printf("\n");
printf("sizeof mychar2 is %d\n", sizeof(mychar2));//sizeof mychar2 is 4,sizeof It's not a function , In fact, it is determined after entering the array sizeof Value .
printf("strlen of mychar2 is %d\n", strlen(mychar2));// strlen of mychar2 is 17, Wrong result , Because the end sign of the character is not detected ,
// And the character array is not initialized , Next, output one by one , Look at this “17” What are the characters
for (int i = 0; i <= strlen(mychar2); i++)
{
printf("%c\n", mychar2[i]); //c bd????????c bdd, The statement ,
}
/* It can be seen that there is no character array end flag , Nor does it initialize a character array that clearly indicates the size of the character array , use strlen() To get the number of characters is wrong .
because strlen It's a function , Parameters are pointers to array names , To retrieve \0 The number of characters before is used as the output result ,
This array is not initialized , The system does not know the specific size , Can't give “ uninitialized ” The element of is filled with \0, So use strlen() When , System not found \0 Where is the , Maybe it's to ensure the front
Accuracy of initialization data , So the system does not stop until it indexes backward to a certain number of characters , But there will also be some garbled code . Use... In this case strlen It's wrong. .
*/
printf("mychar2 is %s\n", mychar2);//c bd Scald... Scald c bdd, The statement ,printf() The function also follows \0 To index .
char mychar3[5] = { 'h', ' ', 't' };// In memory is actually 'h', ' ', 't' ,'\0' ,'\0'
printf("\n");
printf("sizeof mychar3 is %d\n", sizeof(mychar3));//sizeof is 5, Yes sizeof Come on ,\0 Also count in , Because by definition, it opens up 5 Two bytes to store characters , The uninitialized system is set to \0.
printf("strlen of mychar3 is %d\n", strlen(mychar3));//strlen is 3
printf("mychar3 is %s\n", mychar3);//h t
char mychar4[4] = { 'c', ' ', 'b', 'd' };// In memory is 'c', ' ', 'b', 'd'
printf("\n");// Out of commission strlen() function , The calculation result is wrong
printf("sizeof mychar4 is %d\n", sizeof(mychar4));//sizeof is 4
printf("strlen of mychar4 is %d\n", strlen(mychar4));//strlen is 15 .strlen The result is not accurate , Because no \0 Index end flag .
printf("mychar4 is %s\n", mychar4);//c bd Scald... Scald h t
//char mychar5[4] = { 'c', ' ', 'b', 'd', '\0' };// error , Exceeded the defined array size
//==================== Array of strings =========================
char mystr1[5] = "hell";// In memory is 'h','e','l','l','\0', The system automatically sets uninitialized to \0
printf("\n");
printf("sizeof mystr1 is %d\n", sizeof(mystr1));//sizeof mystr1 is 5
printf("strlen of mystr1 is %d\n", strlen(mystr1));//strlen is 4
printf("mystr1 is %s\n", mystr1);//hell
char mystr2[5] = "hello";// In memory is 'h','e','l','l','o', The space allocated for initialization has been fully occupied , The system will not automatically add... Just because it is a string \0
printf("\n");
printf("sizeof mystr2 is %d\n", sizeof(mystr2));// sizeof is 5
printf("strlen of mystr2 is %d\n", strlen(mystr2));//strlen is 20, error , Because according to the initialization definition , There is no end index \0
printf("mystr2 is %s\n", mystr2);//hello Scald scald output ell, The statement , because printf() The function also follows \0 Index to output , Full initialization space but not given \0
printf("mystr2 is %c\n", mystr2);// The output is ?, because mystr2 As printf() Function parameters , Degenerate into a pointer , The output is using mystr2 Address of the ASCII code , It doesn't make sense in practical application .
char mystr3[] = "hello";// For strings with no initialization size , The system does not know the size , Will automatically add one at the end \0
printf("\n"); // In memory is 'h','e','l','l','o','\0' The system automatically adds at the end '\0'
printf("sizeof mystr3 is %d\n", sizeof(mystr3));// sizeof is 6
printf("strlen of mystr3 is %d\n", strlen(mystr3));//strlen is 5
printf("mystr3 is %s", mystr3);//hello
//char mystr3[5] = "hellou";// error , Over array size
return 0;
}For string arrays , If there is still uninitialized space , The system will be set to \0, For string arrays , If there's room , The system will ” kindly “ Add a \0, But if there is no space , The system can't help , such as char a[5]="hello".
The common initialization method of string array is char a[ ]="hello", Do not specify the size , Let the system automatically add a \0.
For character arrays , The system is not so enthusiastic , If the array size is not specified , The system will not add \0 Of , Because the system doesn't know where the end of this array is , Initialized a few characters , The system thinks that this character array is so large 、 But string arrays are different , Yes '' Double quotes " As a determination of scope !
From above , Pay attention to defining characters ( strand ) Array time , Give the appropriate space size , It depends on how it is stored in memory , To make sure strlen() and sizeof Can there be correct results .
//=============20210907 Postscript ======== Made another mistake =============sizeof Not a function, not a function, not a function ! When the array name is used as a parameter, it is not regarded as a pointer, not a pointer !!!!!========================================================================
Now let's look at the code ! Why can't you remember ,sizeof Not a function, not a function, not a function !
Now let's look at the code !!!!
#include<stdio.h>
void Array(int arr[],int size)
{
int i = 0;
for ( i = 0; i < size; i++)
{
arr[i] = i;
//printf("%d\n", arr[i]);
}
printf("sizr of arr[size] in Arr(int*) is %d\n", sizeof(arr));
// Be careful ,sizeof It's not a function , When the array name is used as its parameter , Although the array name is a pointer constant whether it is a function parameter or not ,
// however sizeof It's not a function !!!sizeof( Array name ), What you get is the size of the entire array in bytes , At this time, although the array name is still a pointer constant ,
// however sizeof( Array name ) The value of is really the size of the actual array , Not the size of a pointer , This is also a manifestation that array names only degenerate into pointers as function parameters .
}
int main(int argc, char* argv[])
{
int c[] = { 1, 2, 3 };
int* d = c;
printf("size of c[] is %d\n", sizeof(c));
// In this case, the array name is a function main(int,char*) Parameters of , therefore sizeof(c) Its size is 4!
printf("size of d is %d\n", sizeof(d));
*(c + 1) = 3;
//int s[4] = { 0 };
Array(c,3);
return 0;
}边栏推荐
- The list is not updated in real time when JS V-for data changes
- Connection broken by 'readtimc rt-443): read timed out (read timeout=l5)“)‘: /pac
- SQL语句 关于字段转换怎么写
- How fast does it take to implement a super simple programming language?
- Since 2019, you must have stopped using this marketing strategy
- 从2019 年开始,你一定停止使用了这个营销策略…
- SFTP upload error: com.jcraft.jsch JSchException: connection is closed by foreign host
- Li Kou daily question - day 44 -205. Isomorphic string
- Overestimated test driven development?
- 基于STM32和阿里云的环境检测系统设计
猜你喜欢

Data mining -- code implementation of association analysis example (Part 2)

RHCE的at,crontab的基本操作,chrony服务和对称加密和非对称加密

消费行业数字化升级成 “刚需”,weiit 新零售 SaaS 为企业赋能!

Casbin入门

SQL window function

UCOS任务切换过程

【深度学习CPU(番外篇)——虚拟内存】

Shopify卖家:EDM营销就要搭配SaleSmartly,轻松搞定转化率

What have I learned from 200 machine learning tools?

UCOS task switching process
随机推荐
"Strangers once met" Summer Street Shen Shuyan_ Xia Mo Shen Shuyan's latest chapter
【BGP】小型实验
Tristate gate
Why do programmers so "dislike" the trunk development mode?
sql
Raft protocol - process demonstration
OA项目之会议通知(查询&是否参会&反馈详情)
HCIP BGP
Let variable declaration feature of ES6 new feature and its case
lodash库常用方法
Beijing post network research 2015 problem2
新零售O2O 电商模式解析
数据挖掘——关联分析基础介绍(上)
Data mining -- Introduction to the basis of association analysis (Part 1)
Shutter start white screen
Sunflower senior product director technology sharing: "how to apply national remote control" in AD domain environment
1. Header file - Comment - namespace - standard input / output stream
Common methods of lodash Library
Form verification of landline
Deep understanding of Base64 underlying principles