我试图将一个指针传递给指向过程的指针,但每次都会出现段错误,而将其传递给函数则工作得很好。 我想这可能与 C 在数组到指针上自动执行的强制转换有关,例如在这个问题中: passing a pointer to a pointer in C .
但我不知道如何解决它。
代码如下:
#include <stdio.h>
#include <stdlib.h>
void creer_matrice(int nbCol, int nbLigne, char **matrice)
{
int i,j;
matrice = calloc( nbCol, sizeof(char*));
if( matrice == NULL ){
printf("Allocation impossible");
exit(EXIT_FAILURE);
}
for( i = 0 ; i < nbLigne ; i++ ){
matrice[i] = calloc (nbCol, sizeof(char*));
if( matrice[i] == NULL ){
printf("Allocation impossible");
exit(EXIT_FAILURE);
}
}
/* Remplissage de test*/
for(i = 0; i < nbLigne; i++){
for(j = 0; j < nbCol; j++){
matrice[i][j] = 'I';
}
}
//return matrice;
}
int main(){
int i,j;
char **matrice;
creer_matrice(8,6,matrice);
//matrice = creer_matrice(8,6);
for(i = 0; i < 6; i++){
for(j = 0; j < 8; j++){
printf("%c ",matrice[i][j]);
}
printf("\n");
}
}
有人可以告诉我我错在哪里以及如何解决吗?
最佳答案
更改此行:
for( i = 0 ; i < nbLigne ; i++ ){
matrice[i] = calloc (nbCol, sizeof(char*));
致:
for( i = 0 ; i < nbCol ; i++ ){
matrice[i] = calloc (nbLinge, sizeof(char));
或者更好:在一条语句中为整个矩阵分配内存。
关于c - 将指针传递给 C 过程中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14673103/