初始化使指针从整数而不进行强制转换 - C [英] Initialization makes pointer from integer without a cast - C

查看:94
本文介绍了初始化使指针从整数而不进行强制转换 - C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,如果这篇文章被认为是无知的,但我对 C 仍然很陌生,所以我对它没有很好的理解.现在我正试图找出指针.

Sorry if this post comes off as ignorant, but I'm still very new to C, so I don't have a great understanding of it. Right now I'm trying to figure out pointers.

我编写了这段代码来测试我是否可以在更改函数中更改 b 的值,并通过传入指针将其带回到主函数中(不返回).

I made this bit of code to test if I can change the value of b in the change function, and have that carry over back into the main function(without returning) by passing in the pointer.

但是,我收到一条错误消息.

However, I get an error that says.

Initialization makes pointer from integer without a cast
    int *b = 6

据我所知,

#include <stdio.h>

int change(int * b){
     * b = 4;
     return 0;
}

int main(){
       int * b = 6;
       change(b);
       printf("%d", b);
       return 0;
}

我真的很担心修复这个错误,但如果我对指针的理解完全错误,我不会反对批评.

Ill I'm really worried about is fixing this error, but if my understanding of pointers is completely wrong, I wouldn't be opposed to criticism.

推荐答案

为了让它工作,重写代码如下 -

To make it work rewrite the code as follows -

#include <stdio.h>

int change(int * b){
    * b = 4;
    return 0;
}

int main(){
    int b = 6; //variable type of b is 'int' not 'int *'
    change(&b);//Instead of b the address of b is passed
    printf("%d", b);
    return 0;
}

上面的代码会起作用.

在 C 中,当您希望更改函数中变量的值时,您可以通过引用将变量传递给函数".您可以在此处阅读更多相关信息 - 传递引用

In C, when you wish to change the value of a variable in a function, you "pass the Variable into the function by Reference". You can read more about this here - Pass by Reference

现在错误意味着您正试图将一个整数存储到一个指针变量中,而不进行类型转换.您可以通过如下更改该行来消除此错误(但程序将无法运行,因为逻辑仍然是错误的)

Now the error means that you are trying to store an integer into a variable that is a pointer, without typecasting. You can make this error go away by changing that line as follows (But the program won't work because the logic will still be wrong )

int * b = (int *)6; //This is typecasting int into type (int *)

这篇关于初始化使指针从整数而不进行强制转换 - C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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