簡體   English   中英

使用帶有指向數組的指針的 memset

[英]Using memset with pointer to an array

如何使用指向該數組的指針memset數組?

int *A, n;

printf("\n Enter the size of array : ");
scanf("%d",&n);

A = (int*) malloc(sizeof(*A) * n);

int i = 0;

memset(*A,5,n * sizeof(*A));

for(i = 0; i < n; i++)
    printf("%d ", A[i]);

編譯器不會無緣無故地發出警告:

 warning: passing argument 1 of 'memset' makes pointer from integer without a cast expected 'void *' but argument is of type 'int'

這意味着您沒有將正確的類型傳遞給memset()的第一個參數,它確實需要一個指針,而您正在傳遞一個integer

您的指針A原樣很好,不需要取消引用它( *A )並且是錯誤的,正確的調用是:

memset(A, 5, n * sizeof(*A));

更重要的是,這不是您想要做的! 如果您認為以上將分配的數組的所有元素設置為5 ,則情況並非如此。 相反, memset()每個字節設置5 (請參閱手冊頁)。 由於int超過 1 個字節(通常為 4 個),這將使用值0x05050505 (十進制84215045 )而不是5填充您的數組。

為了將每個元素設置為5您需要一個for循環:

int i = 0; 
for (i = 0; i < n; i++)
    A[i] = 5;

最后, 不要malloc()的返回值

A = malloc(sizeof(*A) * n);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM