为什么这会继续打印“超出范围,请重试”?我该如何解决它
由于某种原因,这将打印出“超出范围,请重试”。我尝试更改IF语句,但这也不起作用。
#define MAX_fn_LEN32
#define MAX_ln_LEN32
#define MAX_stA_LEN64
#define MAX_city_LEN32
#define MAX_state_LEN32
#define MAX_buffer_LEN32
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
int main(){
char* fn=NULL;
bool a=false;
fn = malloc(32 * sizeof(char));;
printf("what is your first name?\n");
scanf("%s",fn);
while(a==false){
if(fn==NULL ||fn>=(32*sizeof(char))){
printf("Out of range try again.\n");
scanf("%s",fn);
a=false;
}
else{
printf("This works.\n");
a = true;
return 0;
}
}
free(fn);
}
由于某种原因,这将打印出“超出范围,请重试”。我尝试更改IF语句,但这也不起作用。
For some reason this will print out "out of range please try again". I tried changing the if statements but that doesn't work either.
#define MAX_fn_LEN32
#define MAX_ln_LEN32
#define MAX_stA_LEN64
#define MAX_city_LEN32
#define MAX_state_LEN32
#define MAX_buffer_LEN32
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
int main(){
char* fn=NULL;
bool a=false;
fn = malloc(32 * sizeof(char));;
printf("what is your first name?\n");
scanf("%s",fn);
while(a==false){
if(fn==NULL ||fn>=(32*sizeof(char))){
printf("Out of range try again.\n");
scanf("%s",fn);
a=false;
}
else{
printf("This works.\n");
a = true;
return 0;
}
}
free(fn);
}
For some reason this will print out "out of range please try again". I tried changing the if statements but that doesn't work either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
if 语句中的条件
没有意义。
将指针
fn
中存储的地址与值32 * ( sizeof( char )
进行比较。看起来你的意思是
但是如果条件确实评估为 true 那么你的程序有未定义的行为。
要检查
fn
是否等于 NULL,您应该在内存分配之后执行此操作,例如The condition in the if statement
does not make a sense.
There is compared an address stored in the pointer
fn
with the value32 * ( sizeof( char )
.It seems you mean
But if the condition indeed evaluates to true then your program has undefined behavior.
To check whether
fn
is equal to NULL you should do after the memory allocation as for example