#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();
}
Ive最近开始在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);
哪种方法正确,哪种方法有效?
您可以直接返回值(无需使用指针)
改变
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中。我只是注意到您的第一个示例已经做到了。您只是在尝试学习指针吗?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句