【发布时间】:2016-03-02 13:46:32
【问题描述】:
我刚开始搞乱结构和指针。
这是我的 .h :
#ifndef struct_struct_h
#include <string.h>
#define struct_struct_h
#endif
int count=0;
typedef struct
{
int num;
double balance;
const char * name;
struct Account * acnt;
} Account;
Account* a = NULL;
Account* new_account(const char * n)
{
Account *a1 = malloc(sizeof(Account));
a1->num=++count;
a1->name = n;
return a1;
}
这是我的 main.c :
#include <stdio.h>
#include <string.h>
#include "struct.h"
int main(int argc, const char * argv[])
{
// insert code here...
Account* accounts[2];
for(int i=0; i<2; i++)
{
accounts[i] = (i==0 ? new_account("David") : new_account("Toto") );
}
printf("Accounts array address is %i\n",&accounts);
for(int i=0; i<2;i++)
{
printf("Account n°%i is owned by %s \n, its address is %i\n",accounts[i]->num,accounts[i]->name,&accounts[i]);
}
printf("There are %i accounts.\n",count);
return 0;
}
如果我用帐户替换 &accounts,我会得到相同的结果:@array,要么是 &accounts[0],没关系。
Accounts数组地址为1606416480
如果我用 *accounts 替换 &accounts,我会得到:
Accounts数组地址为1063600
第二个输出是:
帐户 n°1 归 David 所有 ,它的地址是1606416480
账户 n°2 归 Toto 所有 ,它的地址是1606416488
其实这些是accounts中包含的account指针的@,这些@在内存中各占8B。
如果我将 &accounts[i] 替换为 accounts[i],然后由 *accounts[i] 我得到:
帐户 n°1 归 David 所有 ,它的地址是1063600
账户 n°2 为 Toto 所有,地址为 1063632
帐户 n°1 归 David 所有 ,它的地址是3874
账户 n°2 归 Toto 所有 ,它的地址是3880
在第一种情况下,我有 2 个指针,在第二种情况下,我有 2 个*指针。
*STRUCT 和 STRUCT 不一样,为什么?
【问题讨论】:
-
使用
%p将参数转换为void *以打印地址。 -
如果一个数组是一个指针,它将被称为“指针”,而不是“数组”! &array 不与
array相同。即使 iff 数组 decays 大多数时候都指向一个指针,它也是一个不同的指针。而且你有更多的误解:你的“标题”是错误的。请查看标头必须包含的内容以及守卫的实际用途。 -
我对 C 很陌生,我读过“公共”结构应该在标题中声明。
-
注意:分配问题:使用
Account *a1 = malloc(sizeof *Account);
标签: c arrays pointers reference