#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 = malloc(sizeof(int));
scanf("%d",&ipt);
return ipt;
}
int main(){
int dec = give_options();
printf("decision is: %d", dec);
getchar();
}
我最近开始在Ubuntu中使用C编码 我试图将值返回一个函数的局部变量并将其传递给另一个函数 功能。我已经读过,因为局部变量被分配给堆栈,所以不再有值 函数返回后存在,我必须使用malloc在堆中分配内存。
当我编译时,我得到这个警告:
initialization makes integer from pointer without a cast
[-Wint-conversion] int ipt = malloc(sizeof(int));
当我将其调整为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));
这里做的正确是什么?
因为我在Ubuntu中切换到编码,所以我也遇到了scanf问题。 我尝试了另一种方法,尝试使用指针:
#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);
哪种方法是正确的,哪种方法有效?
答案 0 :(得分:2)
您可以直接返回值(不使用指针)
更改
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();
当函数返回时,函数返回值保留在r0中。 我刚刚注意到你的第一个例子已经做到了。你只是想学习指针吗?