簡體   English   中英

將指針返回數組C時出現帶指針的分段錯誤

[英]Segmentation Fault with Pointers in Returning pointer to array C

我正在嘗試解決一個問題(考慮到當前的代碼框架),並且遇到了指針問題。 我在printf(“%d”,result [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()函數內分配指針(以及將指針返回到同一函數內的數組)在做什么。 我想知道當指向和分配與所述指針不同的值時,我哪部分做錯了。 謝謝。

您的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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM