我正在尝试读取一组数据并收到访问冲突。我可以使用分配数组的函数从数组中读取数据:
AllCurrentData[newLineCount].data[tabCount] = malloc(length + 1);
strcpy( AllCurrentData[newLineCount].data[tabCount], buffer );
printf("%s", AllCurrentData[newLineCount].data[tabCount]);
但是不能在函数外读取。这是我遇到访问冲突的地方,看起来它正在尝试读取空位置。
如何在不同的函数中访问数组 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”(空)。
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] = ...
}
关于c - 读取数组时访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20818238/