我剛開始搞結構和指針。&array == array,結構怎麼樣?
這裏是我的.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;
}
如果我的帳戶替換&賬戶,我得到了相同的結果:@array,要麼是&賬戶[0],沒關係。
帳戶陣列地址是1606416480
如果我更換&應收賬款按*帳戶,我得到這個:
帳戶陣列地址是1063600
第二輸出是:
賬戶N°1由大衛 擁有,其地址爲1606416480
賬戶N°2由託託 擁有,其地址爲1606416488
其實這些帳戶指針的@載在賬戶中,這些@每個8B在內存中。
如果我更換&帳戶[i]發表賬戶[I],然後通過*帳戶[I]我得到:
賬戶N°1由大衛 擁有,其地址爲1063600
帳戶N°2由託託擁有,其地址被1063632
帳戶N°1由大衛 擁有,其地址爲3874
AC計數N°2由託託 擁有,其地址爲3880
在第一種情況我有2個指針,並且在第二I具有2個*指針。
* STRUCT和STRUCT是不同的,爲什麼?
使用'%p'將參數強制轉換爲'void *'來打印地址。 –
如果一個數組是一個指針,它將被稱爲「指針」,而不是「數組」! &array是**不是**與'array'相同。即使** iff **數組_decays_大部分時間都是指向一個指針,它是一個不同的指針。而且你有更多的錯誤觀念:你的「標題」是錯誤的。請查看頭部必須包含的內容以及警衛的實際意圖。 – Olaf
我對C很新,我讀過「公共」結構應該在頭部聲明。 – Aleks