与指针不是在C strcmp的工作 [英] strcmp with pointers not working in C

查看:87
本文介绍了与指针不是在C strcmp的工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这个code不工作。只是试图检查是否用户输入是一样的密码

 的char *通;的printf(写的密码:);
scanf函数(%S,通过); //因为是一个指针和放大器;是吗?
如果(STRCMP(通acopio)== 0)


解决方案

您还没有实际分配任何空间将数据。限定指针只是限定了可容纳的数据的块的地址的变量,它不分配块

您有几个选项,动态分配内存空间关闭堆写进去,使指针指向它。或在堆栈上使用静态分配的内存和它的地址传递给您的来电。还有一点好处动态内存在这种情况下(因为它在使用临时小)。你将有更多的工作要做,如果你使用动态内存 - 你必须确保你有你的要求分配它的时候,确保你已经给它回来时,你就大功告成了,并确保你不使用它的你给它回来后(在棘手的一大应用,相信我!)这只是更多的工作,而你似乎并不需要额外的努力。

下面的例子也需要显著错误检查,但给你的总体思路。

例如

 的char *通=的malloc(SOMESIZE);的printf(写的密码:);
scanf函数(%S,通过);
如果(STRCMP(通acopio)== 0)

 字符通[SOMESIZE]的printf(写的密码:);
scanf函数(%S,通过);
如果(STRCMP(通acopio)== 0)

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)

解决方案

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)

这篇关于与指针不是在C strcmp的工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆