#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Result{
int reversen;
unsigned short count;
};
struct Result *myCount(int, int);
int main()
{
struct Result *result;
myCount(122333, 2);
printf("\nReversed integer of 122333: %d", result->reversen);
printf("\nOccurrence of 2 in 122333: %hu", result->count);
return 0;
}
struct Result * myCount(int n, int d)
{
struct Result * result = (struct Result *) malloc (sizeof (struct Result));
if (result == NULL)
{
fprintf(stderr, "\nNo storage space available\n");
exit(0);
}
int rev_dig, last_dig, digit, count = 0;
while (n != 0)
{
last_dig = n % 10;
rev_dig = rev_dig * 10 + last_dig;
n = n / 10;
}
rev_dig = rev_dig * (-1);
result->reversen = rev_dig;
while (n >= 1)
{
digit = n % 10;
if (digit == d)
count++;
n = n / 10;
}
result->count = count;
}
尝试反转整数值以及符号的变化,并找出数字中出现的数字。
基本上我想我在使用指针时做错了什么。 谁能帮我弄清楚我哪里出错了?
最佳答案
您永远不会在 main()
中初始化 result
并且您永远不会从 myCount()
返回任何内容。
只需在 main()
中执行此操作即可
result = myCount();
记得检查NULL
。
并且在 myCount()
struct Result * myCount(int n, int d)
{
struct Result *result;
int rev_dig;
int last_dig;
int digit;
int count;
count = 0;
result = malloc(sizeof (struct Result));
if (result == NULL)
return NULL; /* handle the error in the caller function */
while (n != 0)
{
last_dig = n % 10;
rev_dig = rev_dig * 10 + last_dig;
n = n / 10;
}
rev_dig = rev_dig * (-1);
result->reversen = rev_dig;
while (n >= 1)
{
digit = n % 10;
if (digit == d)
count++;
n = n / 10;
}
result->count = count;
return result;
}
修复:
如果
malloc()
失败,则返回NULL
,模仿malloc()
的行为。返回指向新分配内存的指针的函数通常会这样做,例如strdup()
.删除了
malloc()
的多余转换。在某个时候返回了
结果
。
不从声明为返回某物的函数返回值是未定义的行为。
关于c - 即使在编译后也会出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33066943/