c - 将指针传递给 C 过程中的指针

标签 c pointers char procedure

我试图将一个指针传递给指向过程的指针,但每次都会出现段错误,而将其传递给函数则工作得很好。 我想这可能与 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/

相关文章:

坂本算法查找星期几的正确性

c++ - linux中的pthread_mutex_t是否可重入(如果一个线程试图获取它已经持有的锁,则请求成功)

c - 从c中的文本文件读取 float 时出现错误值

c - 斐波那契递归

javascript - 比较javascript中的函数指针

c++ - const 数组如何能够在每个元素中仅包含字符,而 char* 数组却能够在每个元素中指向字符串?

c - 为什么代码显示两个不同变量的相同值,temp 既不是本地也不是全局,什么是 temp?

c - 编写一个使用指针和位运算符来更改内存中一位的 C 函数?

java - 3 个连续字符,中间有字母

c - 为什么这个 C 代码给我一个段错误?