簡體   English   中英

設置結構指針的整數會產生分段錯誤

[英]Setting integer of a struct pointer gives segmentation fault

我正在傳遞一個指向結構的指針,並且我想將此結構的成員mn設置為數字33 但是,我遇到了細分問題。 發生了什么?

#include <stdio.h>

typedef struct Matrix {
    int m; //number of lines
    int n; //number of columns
    float* numbers; //elements of our matrix
} Matrix;

void matrix_create(Matrix* a, const float *array, int lines, int columns)
{   
    a->m = lines;
    a->n = columns;
}


int main()
{
    Matrix* a;
    float b[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
    matrix_create(a, b, 3, 3);
    return 0;
}
#include <stdio.h>

typedef struct Matrix {
    int m; //number of lines
    int n; //number of columns
    float* numbers; //elements of our matrix
} Matrix;

void matrix_create(Matrix* a, const float *array, int lines, int columns)
{   
    a->m = lines;
    a->n = columns;
}


int main()
{
    Matrix* a;
    Matrix temp;//Stack Matrix
    float b[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
    a = &temp; //Stack memory
    matrix_create(a, b, 3, 3);
    return 0;
}

這是使用堆棧內存的一種方法,您也可以malloc並使用堆內存

#include <stdio.h>

typedef struct Matrix {
    int m; //number of lines
    int n; //number of columns
    float* numbers; //elements of our matrix
} Matrix;

void matrix_create(Matrix* a, const float *array, int lines, int columns)
{   
    a->m = lines;
    a->n = columns;
}


int main()
{
    Matrix* a = malloc(sizeof(Matrix));
    float b[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
    matrix_create(a, b, 3, 3);
    return 0;
}

這些都應該起作用。

暫無
暫無

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

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