背景關系:https ://stackoverflow.com/a/72238514/15603477
#include<stdio.h>
#include<stdlib.h>
#define MAT_SIZE 2
#define MAT_COUNT 3
typedef double mat[MAT_SIZE][MAT_SIZE];
typedef struct matList{
const char *name;
mat matrix;
}matList;
void init_mat(mat m)
{
for(int i = 0; i < MAT_SIZE; i ){
for(int j = 0; j < MAT_SIZE; j ){
m[i][j] = i * 2.1 (double) j 1.1;
printf("(i,j)=%f\n",m[i][j]);
}
}
}
//allocate matList.
matList *create_mat(const char *name)
{
matList *tempMat = malloc(sizeof *tempMat);
if(tempMat != NULL)
{
tempMat->name = name;
init_mat(tempMat->matrix);
}
return tempMat;
}
// freematList
void free_matList(matList **mats)
{
if(mats){
for(int i = 0; i < MAT_COUNT; i ){
free(mats[i]);
}
}
}
// return non zero if successful
int allocate_matList(matList **mats)
{
if(mats){
mats[0] = create_mat("MAT_A");
mats[1] = create_mat("MAT_B");
mats[2] = create_mat("MAT_C");
if(mats[0] && mats[1] && mats[2])
return 1;
}
}
int main(void)
{
matList *mats[MAT_COUNT];
if(allocate_matList(mats)){
printf("mat[2] name: %s\n",mats[2]->name);
size_t row = sizeof(mats[2]->matrix) / sizeof (mats[2]->matrix[0]);
size_t col = sizeof(mats[2]->matrix[0]) / sizeof(mats[2]->matrix[0][0]);
printf("row: %ld col: %ld\n",row,col);
for(size_t i = 0; i < row; i ){
for(size_t j = 0; j < col; j ){
printf("%f\t",mats[2]->matrix[row][col]);
}
printf("\n");
}
}
free_matList(mats);
exit(EXIT_SUCCESS);
}
結構 matList 會有 MAT_COUNT。每個 matList 的矩陣都是相同的。預期的最后列印結果將是:
1.100000 2.100000
3.200000 4.200000
現在最后一個 printf 回傳
0.000000 0.000000
0.000000 0.000000
這意味著矩陣的賦值失敗?
(gdb) break 23
Breakpoint 1 at 0x11d9: file array_struct170.c, line 23.
(gdb) s
The program is not being run.
(gdb) run
Starting program: /home/jian/helloc/a.out
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Breakpoint 1, init_mat (m=0x5555555592a8) at array_struct170.c:23
23 for(int i = 0; i < MAT_SIZE; i ){
(gdb) s
24 for(int j = 0; j < MAT_SIZE; j ){
(gdb) s
25 m[i][j] = i * 2.1 (double) j 1.1;
(gdb) print m[i][j]
$1 = 0
現在我猜線路有問題是
m[i][j] = i * 2.1 (double) j 1.1;
uj5u.com熱心網友回復:
for(size_t i = 0; i < row; i ){
for(size_t j = 0; j < col; j ){
printf("%f\t",mats[2]->matrix[row][col]); // <- look closely!
}
printf("\n");
由于rowis 2 和colis 2,您正在嘗試列印matrix[2][2],這是超出范圍的。您可能想要matrix[i][j]而不是matrix[row][col].
順便說一句,valgrind立即發現了這一點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/520272.html
標籤:C
上一篇:如何用C語言解決這個陣列問題?
