简体   繁体   English

指向位数组的指针数组

[英]array of pointers to bit arrays

I want to make an array of pointers to bit arrays. 我想制作一个指向位数组的指针数组。 I make this func2 to test the pointers, but I get a seg fault when I try to acess an elemeny of the bit array outside the function. 我将其设为func2来测试指针,但是当我尝试访问函数外部的位数组元素时,出现了段错误。 What am I doing wrong? 我究竟做错了什么?

int func2(int i,  int* bit_array){

  int j;

  for(j = 0; j< i; j++)
    bit_array[j] = malloc(sizeof(int) * i);  

  for(j = 0; j< i; j++)    
   bit_array[j] = 0;

  return 1;
}

int main(){

 int** bit_root;
 bit_root = malloc(sizeof(int *) * 5);

 func2(5, bit_root);

 int n;
 for(n = 0; n < 5; n++)
   printf("%d ", bit_root[0][n]); //error

 printf("\n");

 return 0;
}

You are sending the array incorrect to the function func2 . 您正在将错误的数组发送给函数func2 func2 need to be: func2必须为:

int func2(int i,  int** bit_array){

  int j,k;

  for(j = 0; j< i; j++)
    bit_array[j] = malloc(sizeof(int) * i);  

  for(j = 0; j< i; j++)
    for(k = 0; k< i; k++)  
       bit_array[j][k] = 0;

  return 1;
}

int main(){

 int** bit_root;
 bit_root = malloc(sizeof(int *) * 5);

 func2(5, bit_root);

 int n;
 for(n = 0; n < 5; n++)
   printf("%d ", bit_root[0][n]); //error

 printf("\n");

 return 0;
}

In the lines below you allocate memory for array of int for each element of bit_array and assign pointers to int arrays to bit_array elements: 在下面的几行中,您为bit_array的每个元素为int数组分配内存,并将指向int数组的指针分配给bit_array元素:

for(j = 0; j< i; j++)
  bit_array[j] = malloc(sizeof(int) * i);  

But here you assign zeroes to bit_array elements. 但是在这里,您将零分配给bit_array元素。 Thus you rewrite pointers to zero as if you didn't allocate memore at all: 因此,您将指针重写为零,就好像根本不分配更多信息一样:

for(j = 0; j< i; j++)    
  bit_array[j] = 0;

To fix it replace the this last block this a following code: 要修复它,请在以下代码中替换此最后一个块:

int k;
for(j = 0; j< i; j++)    
  for(k = 0; k < i; k++)
    bit_array[j][k] = 0;

Here in the first loop you iterate through the array of pointers to int arrays (bit_array[j]) and in the inner loop you iterate through the array of ints (bit_array[j][k]). 在第一个循环中,您循环访问int数组的指针数组(bit_array [j]),在内部循环中,您循环访问int数组(bit_array [j] [k])。 These changes requires changing of func2 definition - second parameter must be pointer to pointer to int instead of just a pointer. 这些更改需要更改func2定义-第二个参数必须是指向int的指针的指针,而不仅仅是指针。 It helps you to get rid from warnings of compiler. 它可以帮助您摆脱编译器的警告。 To see what is going on clearly you can use following code: 要查看正在发生的事情,可以使用以下代码:

int k, *int_array = NULL;
for(j = 0; j< i; j++)
{ 
  int_array = bit_array[j]; // get the pointer to int array   
  for(k = 0; k < i; k++)
    int_array[k] = 0; // assign values to int array
}

And don't forget to free all these memory for both inner arrays and bit_array. 并且不要忘记为内部数组和bit_array释放所有这些内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM