0

I am trying to solve a problem (given the current code skeleton) and having trouble with pointers. I am getting a segmentation fault at the printf("%d", result[result_i]); statement in the following code:

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

I am not sure what I'm doing wrong with assigning the pointers within the solve() function (as well as returning the pointer to the array within the same function). I would like to know what part I am doing wrong when pointing and assigning different values from said pointer. Thanks.

1

1 Answer 1

1

Your int* solve function may be the problem.

After allocating memory instead for this array, it should solve the problem.

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

and at the bottom of int main() it is good practice to free the array:

free(result);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for clearing this up! I understand now I need to allocate the memory of an (int) per each cell for an array in C.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.