我的编码作业附带了它的头文件,这意味着我们需要使用相同的数据类型,而不需要改变任何东西。 里面有很多指针,(主要是很多void *)。意思是事情不仅困难,而且令人困惑。 我们必须执行一个单独的函数,只是为了增加指针引用的值。但考虑到程序的性质,我不想不断地提出新的指针。
代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void* intal_create(const char* );
void* intal_increment(void* );
void *intal_create(const char* str)
{
int a;
a=atoi(str);
return &a;
}
void *intal_increment(void *intal)
{
int *a= (int *)intal;//new pointer;
++*a;
//value referenced has been incremented;
*(int *)intal=*a;
return intal;
}
int main()
{
int * x;// void * return a pointer, need a pointert to int to pick it up
char *dummy;
gets(dummy);
x=(int *)intal_create(dummy);
printf("integer return is %d\n",*(int *)x);
printf("address stored is %p\n",(int *)x);
x=(int *)intal_increment(x);
printf("integer return is %d\n",*(int *)x);
printf("address stored is %p\n",(int *)x);
}
我希望 x 成为被调用的参数,并让它存储返回值。 printf地址仅供我理解。
段错误永远不会结束,根据我的理解,我只是返回一个指针并要求指针停止返回指针
最佳答案
合并所有评论。主要是在传递 gets() 函数之前为 dummy 分配内存,并在堆中为 intal_create 的返回指针分配内存。这两个修复解决了该问题。请看下面的代码以供引用。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void* intal_create(const char* );
void* intal_increment(void* );
void *intal_create(const char* str)
{
int *a = (int *)malloc(sizeof(int));
*a = atoi(str);
return a;
}
void *intal_increment(void *intal)
{
//Here i am not allocating
int *a = (int *)intal;//new pointer;
(*a)++;
return intal;
}
int main()
{
int * x;// void * return a pointer, need a pointert to int to pick it up
char dummy[20] = {0};
fgets(dummy,5,stdin);
x = (int *)intal_create(dummy);
printf("integer return is %d\n",*x);
printf("address stored is %p\n",(void*)x);
x=(int *)intal_increment(x);
printf("integer return is %d\n",*x);
printf("address stored is %p\n",(void *)x);
//Make sure you deallocate the memory allocated in the intal_create function.
free(x);
}
关于c - 将指针返回到自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51221690/