首页 文章

返回指向数组C的指针时带指针的分段错误

提问于
浏览
0

我试图解决一个问题(给定当前的代码框架)和指针有问题 . 我在printf上遇到分段错误(“%d”,结果[result_i]);以下代码中的语句:

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int* solve(int a0, int a1, int a2, int b0, int b1, int b2, int *result_size){
    // Complete this function
    *result_size = 2;
    int* scores[*result_size];

    *scores[0] = ((a0>b0)?1:0)+ ((a1>b1)?1:0)+ ((a2>b2)?1:0);
    *scores[1] = ((a0<b0)?1:0)+ ((a1<b1)?1:0)+ ((a2<b2)?1:0);

    return *scores;
}

int main() {
    int a0; 
    int a1; 
    int a2; 
    scanf("%d %d %d", &a0, &a1, &a2);
    int b0; 
    int b1; 
    int b2; 
    scanf("%d %d %d", &b0, &b1, &b2);
    int result_size;
    int* result = solve(a0, a1, a2, b0, b1, b2, &result_size);
    for(int result_i = 0; result_i < result_size; result_i++) {
        if(result_i) {
            printf(" ");
        }
        printf("%d", result[result_i]);
    }
    puts("");


    return 0;
}

我不确定在resolve()函数中指定指针(以及在同一函数中返回指向数组的指针)我做错了什么 . 我想知道在指向和分配来自所述指针的不同值时我做错了什么部分 . 谢谢 .

1 回答

  • 1

    您的int * solve函数可能是问题所在 .

    在为这个数组分配内存之后,它应该解决问题 .

    int* solve(int a0, int a1, int a2, int b0, int b1, int b2, int *result_size){
        // Complete this function
        *result_size = 2;
        int* scores = malloc(sizeof(int) * (*result_size));
    
        scores[0] = ((a0>b0)?1:0)+ ((a1>b1)?1:0)+ ((a2>b2)?1:0);
        scores[1] = ((a0<b0)?1:0)+ ((a1<b1)?1:0)+ ((a2<b2)?1:0);
    
        return scores;
    }
    

    在int main()的底部,最好释放数组:

    free(result);
    

相关问题