c - 传入指向整数指针的指针时的斐波那契数列

标签 c pointers sequence fibonacci

我试图传入一个指向整数指针的指针,其中包含它想要的值的数量。该函数必须编辑传入的整数数组。

第二个问题:既然传入的是数组地址,是否需要存储在动态分配的数组中?

#include <stdlib.h>
#include <stdio.h>    

void fib(int **fib_sequence, int values) {
    fib_sequence = malloc(values * sizeof(int)); // this line may be unnecessary
    *fib_sequence[0] = 0;
    *fib_sequence[1] = 1;
    int i;
    for (i = 2; i < values; i++) {
        *fib_sequence[i] = *fib_sequence[i-1] + *fib_sequence[i-2];
    }
}

int main(int argc, char **argv) {
    int count = strtol(argv[1], NULL, 10);
    int *fib_sequence;
    fib(&fib_sequence, count);    
    printf("%d", fib_sequence[count - 1]);
    return 0;
}

最佳答案

更好的 malloc 在函数之外并保存额外的间接级别。还添加一些参数检查并为 count 使用正确的类型。不要忘记在最后释放你的内存。

#include <stdlib.h>
#include <stdio.h>    

void fib(int *fib_sequence, int values) {
    fib_sequence[0] = 0;
    fib_sequence[1] = 1;
    int i;
    for (i = 2; i < values; i++) {
        fib_sequence[i] = fib_sequence[i-1] + fib_sequence[i-2];
    }
}

int main(int argc, char **argv) {
    if (argc != 2)
    {
      fprintf(stderr, "Usage: %s <number>\n", argv[0]);
      return 1;
    }

    long count = strtol(argv[1], NULL, 10);
    int *fib_sequence = malloc(count * sizeof(int));
    fib(fib_sequence, count);    
    printf("%d\n", fib_sequence[count - 1]);
    free(fib_sequence);
}

最好在每条语句后检查errno 的值。这样,如果您输入负值,您将收到错误消息而不是段错误。

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define CHKERR()                                                \
    if ( errno != 0 )                                           \
    {                                                           \
        perror("Error in " __FILE__ ":" TOSTRING(__LINE__));    \
        return 1;                                               \
    }

void fib(int *fib_sequence, int values) {
    fib_sequence[0] = 0;
    fib_sequence[1] = 1;
    int i;
    for (i = 2; i < values; i++) {
        fib_sequence[i] = fib_sequence[i-1] + fib_sequence[i-2];
    }
}

int main(int argc, char **argv) {
    if (argc != 2)
    {
        fprintf(stderr, "Usage: %s <number>\n", argv[0]);
        return 1;
    }

    long count = strtol(argv[1], NULL, 10); CHKERR();

    int * fib_sequence = malloc(count * sizeof(int)); CHKERR();

    fib(fib_sequence, count);

    printf("%d\n", fib_sequence[count - 1]); CHKERR();

    free(fib_sequence);
}

关于c - 传入指向整数指针的指针时的斐波那契数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44233239/

相关文章:

c - 通过 SSL 和 TLS 绑定(bind)并验证到 LDAP 服务器

char 指针未返回正确的值

python - numpy.loadtxt "could not convert string to float"

animation - 按顺序链接 Action 和动画

c - OpenGL SOIL 连接到 Visual Studio

c - 将 3D 数组(字符串的 2D 数组)传递给函数并在那里编辑它

c - 在结构中定义宏背后的逻辑是什么?

c - (C) strtok 具有多个空格/制表符,用指针检查 null

c - 在c中初始化双指针的正确方法是什么

postgresql - 异常 : relation does not exist with postgresql table/sequence in ejb3