这在x86中编译很好,但是当我在x64配置中使用它时,x和y变量在我尝试访问时没有地址?是否需要某种填充以对齐更大的地址?使用MSVC ..
#define ARR_SIZE 25
typedef struct {
unsigned int x;
unsigned int y;
}Stuff;
void allocateArray(Stuff *stuffArr) {
Stuff *stuff = malloc(sizeof (Stuff) * ARR_SIZE);
for (int i = 0; i < ARR_SIZE; i++) {
(*(stuff + i)) = (Stuff) { i, i + i };
}
for (int i = 0; i < ARR_SIZE; i++) {
printf("%d : %d\n", (stuff + i)->x, (stuff + i)->y);
}
stuffArr = stuff;
}
void deallocateArray(Stuff *stuffArr) {
free(stuffArr);
}
int main(){
Stuff * stuff = NULL;
allocateArray(stuff);
deallocateArray(stuff);
return 0;
}
答案 0 :(得分:4)
正如user3386109所说,代码不正确。您可能期望allocateArray()
函数返回已分配的指针,而您正在按值传递指针,以便stuff
内的变量main()
不会更新。
你可以:
allocateArray()
签名更改为void allocateArray(Stuff **stuffArr)
allocateArray()
签名更改为Stuff *allocateArray()
(第二个将更加惯用和明确)。
我把它写成:
Stuff *allocateArray(size_t count) {
Stuff *stuff = (Stuff *) malloc(sizeof (Stuff) * count);
if (! stuff)
return NULL;
for (int i = 0; i < count; i++) {
stuff[i].x = i;
stuff[i].y = 2 * i;
printf("%d : %d\n", stuff[i].x, stuff[i].y);
}
return stuff;
}
void deallocateArray(Stuff *stuffArr) {
if (stuffArr)
free(stuffArr);
}
int main(){
Stuff * stuff = allocateArray(ARR_SIZE);
deallocateArray(stuff);
return 0;
}
答案 1 :(得分:2)
当您在allocateArray中传递内容时,您创建了一个局部变量,当您在函数末尾重新设置它时,main中的变量不会更新
这应该有效,你刚刚在allocateArray函数中丢失了指针
#define ARR_SIZE 25
typedef struct {
unsigned int x;
unsigned int y;
}Stuff;
Stuff *allocateArray() {
Stuff *stuff = malloc(sizeof (Stuff) * ARR_SIZE);
for (int i = 0; i < ARR_SIZE; i++) {
(*(stuff + i)) = (Stuff) { i, i + i };
}
for (int i = 0; i < ARR_SIZE; i++) {
printf("%d : %d\n", (stuff + i)->x, (stuff + i)->y);
}
return stuff;
}
void deallocateArray(Stuff *stuffArr) {
free(stuffArr);
}
int main(){
Stuff * stuff = NULL;
stuff = allocateArray();
deallocateArray(stuff);
return 0;
}
答案 2 :(得分:2)
我将您的代码复制并粘贴到Visual Studio 2015中,并在x86和x64中进行编译,并且两次都得到完全相同的输出,但是就像user3386109所说的那样,您实际上并没有更改stuff
中的变量main
1}}。
你也可以使用数组索引而不是像这样的指针添加整数。
for (int i = 0; i < ARR_SIZE; i++) {
stuff[i] = (Stuff) { i, i + i };
}
for (int i = 0; i < ARR_SIZE; i++) {
printf("%d : %d\n", stuff[i].x, stuff[i].y);
}
答案 3 :(得分:0)
好问题是它在x86中是如何工作的。 (这是未定义的行为)。 试试这个:
#define ARR_SIZE 25
#include "stdlib.h"
#include "stdio.h"
typedef struct {
unsigned int x;
unsigned int y;
}Stuff;
void * allocateArray(Stuff *stuffArr) { //this row
Stuff *stuff = (Stuff*)malloc(sizeof (Stuff) * ARR_SIZE);
for (int i = 0; i < ARR_SIZE; i++) {
(*(stuff + i)) = (Stuff) { i, i + i };
}
for (int i = 0; i < ARR_SIZE; i++) {
printf("%d : %d\n", (stuff + i)->x, (stuff + i)->y);
}
stuffArr = stuff;
return stuff; //this row
}
void deallocateArray(Stuff *stuffArr) {
free(stuffArr);
}
int main(){
Stuff * stuff = NULL;
printf("%d\n",stuff);
stuff=(Stuff*)allocateArray(stuff); ///this row
printf("%p\n",stuff);
deallocateArray(stuff);
printf("%p\n",stuff);
return 0;
}