c – 读取数组时的访问冲突

我试图读取数据数组并接收访问冲突。 我可以使用以下函数从数组中读取数组中的数据:

AllCurrentData[newLineCount].data[tabCount] = malloc(length + 1); strcpy( AllCurrentData[newLineCount].data[tabCount], buffer ); printf("%s", AllCurrentData[newLineCount].data[tabCount]); 

但是在function之外无法读取它。 这是我获得访问冲突的地方,看起来它正在尝试读取空位置。

如何在不同的函数中访问数组AllCurrentData中的数据? 谢谢!

额外信息:

 typedef struct current{ char **data; }CurrentData; 

AllCurrentData在main中声明:

 CurrentData *AllCurrentData = '\0'; 

函数调用

 getCurrentData(current, AllCurrentData); printf("%s", AllCurrentData[0].data[0]); //<----- error here 

 CurrentData *AllCurrentData = '\0'; 

这声明了一个指针。 该指针是一个变量,它包含一个被解释为地址的数字。 您将指针初始化为’\ 0’(null)。

 getCurrentData(current, AllCurrentData); 

在这里,您将此指针作为参数传递给函数getCurrentData 。 由于指针是变量,因此该变量通过值传递,这意味着该函数接收该值的副本(表示地址的数字)。

如果你写的话,在函数内部

 AllCurrentData = malloc... 

你修改了指针的副本,所以在函数AllCurrentData之外仍然是’\ 0’。 你需要传递一个指向该指针的指针(我知道是Inception)。

 getCurrentData(current, &AllCurrentData); getCurrentData(.., CurrentData **p_AllCurrentData) { *p_AllCurrentData = malloc(...); } 

让我在一个更简单的例子中解释这个概念:

 int *v = NULL; // here v is a pointer. This pointer has value 0 (invalid address) v = malloc(10 * sizeof(int)); // here the pointer is assigned a valid address, lets say 0x41A0 f(v); void f(int *x) { // here the pointer x receives a copy of the value of the pointer v, so x will be, like v, 0x41A0 x[0] = 4; /*this is ok as you modify the memory at the address 0x41A0, so this modification is seen from outside the function, as v points to the same address.*/ x = malloc(...); /* this is NOT ok, as x receives a new address, lets say 0xCC12. But because x has a copy of the value from v, v will still be unmodified.*/ } 

所以如果你想在函数内部分配一个指针,那就不行了:

 int *v = NULL; // here v is a pointer. This pointer has value 0 (invalid address) f(v); void f(int *x) { // here the pointer x receives a copy of the value of the pointer v, so x will be, like v, NULL x = malloc(...); /*this is NOT ok, as x receives a new address, lets say 0xCC12. But because x has a copy of the value from v, v will still be unmodified, it will still have NULL.*/ } 

正确的方法是:

 int *v = NULL; // here v is a pointer. This pointer has value 0 (invalid address) // as v is a variable (of type pointer to int), v has an address, lets say 0xAAAA. f(&v); void f(int **p_x) { /* here the p_x is a pointer to (a pointer of int), so this pointer receives a copy of the value the address of p, so p_x is 0xAAAA.*/ *p_x = malloc(...); /* lets say malloc returns the address 0xBBBB. This will be the address of our vector. *p_x= says we modify the value at the address p_x. So the value found at the adress 0xAAAA will be 0XBBBB. But because 0xAAAA is the address of v, we effectively modified the value of v to 0xBBBB. So now v has the address of our starting vector.*/ // if you want to modify values inside this vector you need: (*p_x)[0] = ... }