gpt4 book ai didi

c - 当我来自 C 中的另一个函数时,无需 memset 即可工作

转载 作者:行者123 更新时间:2023-11-30 20:27:28 32 4
gpt4 key购买 nike

当我来自 success() 函数时,我不需要将内容设置回 0 但当我在同一函数内循环序列时我必须使用 memset(psswrd,0,sizeof(psswrd)); 将 psswrd 的内存设置回 0 其大小,那么当我来自另一个函数时,它在没有 memset 的情况下工作有什么区别?

<小时/>

在其他用户对我的代码进行评论后(感谢批评,我从中吸取了教训),我使用新循环对其进行了修改,并且我的问题现在通过此代码变得无敌了,所以我的一个新问题是为什么当例如,我来自另一个函数,例如 success(),我不需要将其内存设置回 0?它是否会因为声明而自动设置回默认初始化?

#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#include <string.h>
#include <process.h>

success(){
clrscr();
printf("Press Any Key to Go Back and Login ");
getch();
return 0;
}

int cnt;
void login(){
char ch,
mypass[]="thepass",
psswrd[256]={0};
do{
cnt=NULL;
memset(psswrd,0,sizeof(psswrd));
clrscr();
printf("Enter Password: ");
do{
ch=getch();
if( isprint(ch) ){
psswrd[ cnt++ ] = ch;
printf("%c", ch);
}
else
if(ch==8 && cnt){
psswrd[ cnt-- ] = '\0';
printf("%s", "\b \b");
}
}
while(ch!=13);
}
while(strcmp(psswrd,mypass));
}

void main(){
do{
login();
success();
}
while(!success());
}

最佳答案

psswrd 永远不会为空。它是一个数组并且始终具有相同的大小。在您的情况下,它始终是 8 个字符大(您指定的 7 个字符加上末尾自动插入的 \0 字符。)

“清空”字符串意味着将其长度设置为零。在 C 中,约定认为字符串在第一次出现 \0 时结束。因此,为了将长度设置为零,您只需将字符数组的第一个元素设置为 0。您不需要 memset() 整个事情:

psswrd[0] = 0;

cnt为0时(它是一个int,所以NULL只是令人困惑),那么上面就是发生的事情,字符串是被认为是零长度,因此是空的。

关于c - 当我来自 C 中的另一个函数时,无需 memset 即可工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19614189/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com