简体   繁体   English

C,为什么我不能声明指针并初始化它?

[英]C, Why can't I declare pointer and initialize it?

Well, I have the following code: 好吧,我有以下代码:

int main(int argc, char **argv, char **envp)
{
    const char *usuario= NULL;
    while(*envp)
    {
        char *str = *envp++;
        //if(strcmp(str,"USERNAME")==0)
        if(str[0] == 'U' && str[1] == 'S' && str[2]=='E' && str[3]=='R' && str[4] == 'N')
        {
            usuario = str;
            break;
        }
    }
    if(usuario != NULL)
    {
        printf("Hola, bienvenido al programa %s",usuario);
    }
    return 0;
}

And my question is why can't I declare the variable outside the while and initialize it inside? 我的问题是为什么我不能在while外部声明变量并在内部将其初始化?

char *str;
const char *usuario= NULL;
while(*envp)
{
    *str = *envp++;
    if(`...

The compiler says: warning: assignment makes integer from pointer without a cast 编译器说: 警告:赋值从指针进行整数转换而无需强制转换

warning: assignment makes integer from pointer without a cast 警告:赋值使指针从整数变为整数而不进行强制转换

The problem is that you're not assigning to your pointer, you're assigning to the value that the pointer points to: 问题是您没有分配给指针,而是分配给指针指向的值:

*str = *envp++;

The * before str causes the pointer to be dereferenced. str前面的*导致指针被取消引用。 Instead, you probably want: 相反,您可能想要:

str = *envp++;

So the problem with this *str = *envp++; 所以这个*str = *envp++; is that you are referencing the str pointer and then assigning a pointer to a char. 是您要引用str指针,然后将一个指针分配给char。 In other words: 换一种说法:

str is a pointer to a char str是指向char的指针

*envp is a pointer to a char * envp是指向char的指针

Thus 从而

str = *envp++ str = * envp ++

would be a correct statement since both are pointers to a char. 正确的陈述,因为两者都是指向char的指针。 But in the provided code you are doing the following: 但是在提供的代码中,您正在执行以下操作:

*str is a char * str是一个字符

*envp is a pointer to a char * envp是指向char的指针

This means that you are trying to assign a "pointer to a char" to a char. 这意味着您试图将“ char指针”分配给char。 The types do not match. 类型不匹配。

So fix this by changing your code like this: 因此,通过更改代码来解决此问题:

char *str;
const char *usuario= NULL;
while(*envp)
{
    str = *envp++;
    if(... `

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM