在C语言中,如何将局部函数变量值传递给另一个函数,并在没有错误的情况下打印值
当我将其调整为int ipt=(int)malloc(sizeof(int))-我得到: 在这里正确的做法是什么 自从我改用Ubuntu编写代码以来,我在scanf方面也遇到了麻烦。 我尝试了另一种方式,尝试使用指针:在C语言中,如何将局部函数变量值传递给另一个函数,并在没有错误的情况下打印值,c,pointers,ubuntu,printf,scanf,C,Pointers,Ubuntu,Printf,Scanf,当我将其调整为int ipt=(int)malloc(sizeof(int))-我得到: 在这里正确的做法是什么 自从我改用Ubuntu编写代码以来,我在scanf方面也遇到了麻烦。 我尝试了另一种方式,尝试使用指针: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast] int ipt = (int)malloc(sizeof(int)); 哪种方法正确,哪种方法有效?您可以直接返回值(
warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
int ipt = (int)malloc(sizeof(int));
哪种方法正确,哪种方法有效?您可以直接返回值(无需使用指针) 改变
warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int **’ [-Wformat=]
scanf("%d",&ipt);
warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("decision is: %d", dec);
到
及
到
你也可以离开
int ipt;
scanf("%d", &ipt);
作为
函数返回时,函数返回值保留在r0中。
我刚刚注意到您的第一个示例已经做到了这一点。您只是想学习指针吗?
malloc(sizeof(int))
返回一个指向已分配内存的指针。为什么代码使用intipt=malloc(sizeof(int))保存指向int
的指针代码>scanf(“d”和ipt)代码>-->scanf(“%d”,ipt)代码>因为ipt
是一个指针(在第二个示例中)。@johnnymapp“d”
-->%d”
@BLUEPIXY谢谢。我已经知道了。@kanr返回一个局部变量是可以的。你不应该做的是返回一个指向局部变量的指针。也许要注意,这样你就不需要包含free(dec)调用give_options()
后,在调用函数中的某个位置执行code>操作。
#include <stdio.h>
#include <stdlib.h>
int* give_options();
int* give_options(){
printf("===== MENU 1 =====\n");
printf("> store new customer :\t\tenter 1\n");
printf("> view a customer :\t\tenter 2\n");
printf("> view all customers :\t\tenter 3\n");
printf("> exit program :\t\tenter 4\n ");
int* ipt;
ipt = malloc(sizeof(int));
scanf("d",&ipt);
return ipt;
}
int main(){
int* dec = give_options();
printf("decision is: %d", dec);
getchar();
}
warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int **’ [-Wformat=]
scanf("%d",&ipt);
warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("decision is: %d", dec);
int* give_options();
int give_options(){
int* ipt;
ipt = malloc(sizeof(int));
scanf("d",&ipt);
int ipt;
scanf("%d", &ipt);
int* dec = give_options();
int dec = give_options();