传入指向整数指针

时间:2017-05-29 00:25:32

标签: 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;
}

1 个答案:

答案 0 :(得分:3)

在函数外部更好malloc并保存额外的间接级别。还要添加一些参数检查并使用count的正确类型。不要忘记free你的记忆。

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