return from function changes value of array element in c

100 Views Asked by At

I am trying to implement a function which fills a struct, including an int array[3][31]. Inside the function everything is fine but when I return a pointer to my struct and print it out in the main function the elements [1][0] and [2][0], which should both be 0, are 32 and 4.

I already went over it with the debugger but the values just change as soon as it leaves the function.

Here are the relevant parts of my function:

struct monat* create_monat(int zahl_tage, int erster_tag){
    int wochen_tage[] = {1, 2, 3, 4, 5, 6, 7};
    monat* neuer_monat = malloc(sizeof(monat));
    int count =0;
    while(neuer_monat->kalender[0][count] !=2){
        int wochen_tag = wochen_tage[(erster_tag-1 +count) %7];

        neuer_monat->kalender[0][count] = count+1;

        neuer_monat->kalender[1][count] = wochen_tag;

        if((wochen_tag == 7) || (wochen_tag == 6)){
            neuer_monat->kalender[2][count] =1;
        }
        else{
            neuer_monat->kalender[2][count] =0;
        }
        count++;
    }
    return neuer_monat;
}

And I am calling it with this


int main(){

    monat* jan24 = create_monat(31, 1);
    for(int i=0; i<3; i++){
        for(int u=0; u<31; u++){
            printf("%.2d ", jan24->kalender[i][u]);
        }
        printf("\n");
    

Can somebody help please?

1

There are 1 best solutions below

0
EnderMega On

Use neuer_monat->kalender[0][count] != 1 and not neuer_monat->kalender[0][count] != 2.

I also changed so it uses a for loop.

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

struct monat {

    int kalender[3][31];
};

monat* create_monat(int zahl_tage, int erster_tag)
{
    int wochen_tage[] = { 1, 2, 3, 4, 5, 6, 7 };
    monat* neuer_monat = (monat*)malloc(sizeof(monat));
    if (!neuer_monat)
        return 0;

    for (int count = 0; neuer_monat->kalender[0][count] != 1; count++)
    {
        int wochen_tag = wochen_tage[(erster_tag - 1 + count) % 7];

        neuer_monat->kalender[0][count] = count + 1;

        neuer_monat->kalender[1][count] = wochen_tag;

        if ((wochen_tag == 7) || (wochen_tag == 6))
            neuer_monat->kalender[2][count] = 1;
        else
            neuer_monat->kalender[2][count] = 0;
    }

    return neuer_monat;
}

int main()
{
    monat* jan24 = create_monat(31, 1);

    for (int i = 0; i < 3; i++)
    {
        for (int u = 0; u < 31; u++)
        {
            printf("%.2d ", jan24->kalender[i][u]);
        }

        printf("\n");
    }

    return 0;
}