我是C編程新手,我對指針數學感到困惑。我有一個大小爲32的字符數組。我的理解是,這意味着該數組也是32個字節,因爲字符變量是1個字節,因此32 characters * 1 byte = 32 bytes
。問題是當有一個函數有一個void指針指向前面描述的字符數組。我相信代碼段指針運算與陣列
for (count = 0; count < size; count++)
*((int*) raw_sk + count) = 0
應將所有插槽中raw_sk緩衝區應設置爲0。但是,當我運行該程序,我得到一個分段錯誤。我認爲這可能是事實,我正在計算地址。我認爲,如果我將一個地址添加到地址,我將移動到陣列中的下一個插槽。有人可以指出我要去哪裏嗎?我正在使用的功能如下。 謝謝!
void
write_skfile (const char *skfname, void *raw_sk, size_t raw_sklen)
{
int fdsk = 0;
char *s = NULL;
int status = 0;
int count = 0;
int size = (raw_sklen);
/* armor the raw symmetric key in raw_sk using armor64 */
s = armor64(raw_sk, raw_sklen);
/* now let's write the armored symmetric key to skfname */
if ((fdsk = open (skfname, O_WRONLY|O_TRUNC|O_CREAT, 0600)) == -1) {
perror (getprogname());
/*scrubs the armored buffer*/
for(count = 0; count < armor64len(s); count++)
s[count] = '0';
free (s);
/* scrub the buffer that's holding the key before exiting */
for (count = 0; count < size; count++)
*((int*)raw_sk + count) = 0;
exit (-1);
}
else {
status = write (fdsk, s, strlen (s));
if (status != -1) {
status = write (fdsk, "\n", 1);
}
for (count = 0; (size_t)count < 22; count++)
*((int*)raw_sk + count) = 0;
free (s);
close (fdsk);
/* do not scrub the key buffer under normal circumstances
(it's up to the caller) */
if (status == -1) {
printf ("%s: trouble writing symmetric key to file %s\n",
getprogname(), skfname);
perror (getprogname());
/* scrub the buffer that's holding the key before exiting */
/* scrub the buffer that's holding the key before exiting MY CODE
for (count = 0; count < size; count++)
*((int*)raw_sk + count) = 0;*/
exit (-1);
}
}
}
所以我怎麼能增加一個字符的大小?我認爲編譯器會爲我做這件事,顯然我錯了。我將研究如何使用memset。 – tpar44 2012-03-07 21:44:39
Memset做到了!謝謝! – tpar44 2012-03-07 21:57:03
@ tpar44:您正在將'raw_sk'投射到'int *'。指針算術知道如何增加指針的類型。例如,向char指針加1會使指針增加1個字節。向int指針加1會增加4個字節(大部分時間)。我們可以概括這一點,並且說* * * *類型的指針增加* n *會使指針增加'n * sizeof(x)'。所以,如果你把'raw'_sk'改成'char *',那就沒問題了。當然,實現它的慣用方法是創建一個臨時指針,並簡單地增加該指針,而不是添加「count」變量。 – 2012-03-07 22:10:37