2017-10-18 41 views
0

我寫一個Visual C++程序獲取打印作業的詳細信息。 代碼如下所示:調用API WINSPOOL問題GetJOB

HANDLE hPrinter; 
DWORD needed, returned, byteUsed,level; 
JOB_INFO_2 *pJobStorage1=NULL; 
level = 2; 

GetJob(hPrinter, jobId, level, NULL, 0, &needed); 
if (GetLastError()!=ERROR_INSUFFICIENT_BUFFER) 
    cout << "GetJobs failed with error code" 
    << GetLastError() << endl; 
pJobStorage1 = (JOB_INFO_2 *)malloc(needed); 
ZeroMemory(pJobStorage1, needed); 
cout << GetJob(hPrinter, jobId, level, (LPBYTE)pJobStorage1, needed, (LPDWORD)&byteUsed) << endl; 
cout << pJobStorage1[0].pPrinterName<<endl; 

按照documentation,pJobStorage1的輸出不是數組,但是,當我更改IDE報錯

pJobStorage1[0].pPrinterName 

pJobStorage1.pPrinterName 

所以,我想知道發生了什麼。

+0

它不是一個數組。你將它正確地聲明爲一個指針,並且做了內存管理權(不要忘記free(),讓我們不要對新的vs malloc進行挑剔),你只需要' - >'來解引用它。荷蘭荷蘭。 –

回答

0

你有一個指針。只要看到聲明JOB_INFO_2 *pJobStorage1=NULL

隨着pJobStorage1[0].pPrinterNamepJobStorage1->pPrinterName你訪問第一個元素pJobStorage1 ist指向。

pJobStorage1.pPrinterName是無效的,因爲pJobStorage1,你不能用一個指針去除一個指針。運營商。

如果你定義數組JOB_INFO_2 foo[5]。 foo本身就是指向第一個數組元素的地址/指針。所以你可以使用foo而不是JOB_INFO_2 *。所以,如果你有一個數組名稱,你可以使用它而不是一個指針。一個指針也定義了一個特定類型的元素的地址。您可以將其用作數組。

指針和數組具有可互換的使用。

struct A 
{ 
    int a; 
}; 

void Foo() 
{ 
    A a[3], *pa; 
    pa = a; 

    A b; 
    // Accessing first element 
    b = *a; 
    b = a[0]; 
    b = pa[0]; 
    b = *pa; 

    // Accessing second element 
    b = a[1]; 
    b = pa[1]; 
    b = *(pa+1); 

    // accessing member in first element. 
    int c; 
    c = a[0].a; 
    c = pa[0].a; 
    c = pa->a; 
    c = (*pa).a; 
} 
+0

是否可以使用的對象?運營商只能訪問會員? 對於指針,我可以使用 - >運算符來訪問成員只? –

+0

不可以。您可以取消指針並使用該指針。改變了我的答案,看最後一行。 – xMRi