Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

strcmp with pointers not working in C

Why this code isn't working. Just trying to check if the user input is the same as a password

char *pass;

printf("Write the password: ");
scanf("%s", pass); // Because is a pointer the & is out ?


if( strcmp( pass , "acopio") == 0)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You've not actually allocated any space to put data. Defining a pointer just defines a variable that can hold the address of a block of data, it doesn't allocate the block.

You have a couple of options, allocate dynamic memory off the heap to write into and make the pointer point to it. Or use statically allocated memory on the stack and pass the address of it to your calls. There's little benefit to dynamic memory in this case (because it's temporary in use and small). You would have more work to do if you used dynamic memory - you have to make sure you got what you asked for when allocating it and make sure you've given it back when you're done AND make sure you don't use it after you've given it back (tricky in a big app, trust me!) It's just more work, and you don't seem to need that extra effort.

The examples below would also need significant error checking, but give you the general idea.

e.g.

char *pass = malloc (SOMESIZE);

printf("Write the password: ");
scanf("%s", pass);


if( strcmp( pass , "acopio") == 0)

or

char pass[SOMESIZE];

printf("Write the password: ");
scanf("%s", pass);


if( strcmp( pass , "acopio") == 0)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...