c - 即使在编译后也会出现段错误?

标签 c

#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;
}

修复:

  1. 如果 malloc() 失败,则返回 NULL,模仿 malloc() 的行为。返回指向新分配内存的指针的函数通常会这样做,例如strdup().

  2. 删除了 malloc() 的多余转换。

  3. 在某个时候返回了结果

不从声明为返回某物的函数返回值是未定义的行为

关于c - 即使在编译后也会出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33066943/

相关文章:

c++ - 将字符数组传递给 CUDA 内核

c - 算术右移后出现意外结果

c - 子进程之间的 UNIX 管道

c - ResumeThread 在这种特殊情况下不起作用

c - C 中 main() 的不同约定

c - 文件处理中的段错误

c - 注入(inject)数据包以终止 TCP 连接

c - 当接口(interface)有 >1 个 IPv6 地址时 Linux IPv6 源地址选择 : How to deprecate one?

c - fgets() 在 popen() 之后不起作用

c - 使用 C,if 语句不起作用(使用 fork 和子进程来运行程序的某些部分)