char* username[30];
memset(username,0x00,30);
scanf("%s",&username);
這會使指針指向內存中的隨機位置還是安全使用?使用scanf指針陣列
char* username[30];
memset(username,0x00,30);
scanf("%s",&username);
這會使指針指向內存中的隨機位置還是安全使用?使用scanf指針陣列
char *username[30]
是指針的數組,而不是字符。所以你的代碼是非常錯誤的(如在不是安全)。要獲得字符數組,你需要:
char username[30];
char* username[30]; //is array of char pointers.
//Allocate memory for these pointers using calloc(). so no need of memset().
memset(username,0x00,30);//can be removed.
scanf("%s",&username);//It should be scanf("%s",username[i]);
@perreal,樣品添加。
#define SIZE 100 //100 chars...
char* username[30];
int i;
for(i = 0; i < 30; i++)
{
username[i] = calloc(SIZE, sizeof(char)); //Add Fail checks if needed.
scanf("%s",username[i]);
}
所以用上面的代碼,你可以得到30個字符串。如果您只需要一個帶30個字符的字符串,那麼
char username[30];
memset(username,0x00,30);
scanf("%s",username);
就足夠了。
與
memset(username,0x00,30);
要初始化前30個字節的指針數組,而不是整個陣列
memset(username,0, sizeof(username));
會雖然一個簡單的循環是讓讀者更清晰的一切設置爲0 (恕我直言)
for (int i = 0; i < 30; username[i++] = NULL) {;}
不這樣做:
scanf("%s",&username);
scanf不神奇地分配任何東西 - 「用戶名」是一個指針數組,並且是空指針,scanf如何知道如何分配內存等?而是做一個循環,讓用戶輸入一個字符串,爲該字符串分配內存(+1),將該字符串複製到分配的內存並將其分配給「username [i]」。
你可能想要的是:
int i;
char* username[30];
for(i = 0; i < 30; i++)
{
username[i] = calloc(100, sizeof(char)); // or whatever size your string is.
scanf("%s",username[i]);
}
... Code using usernames ...
for(i = 0; i < 30; i++)
{
free(username[i]);
}
但就個人而言,我可能會去:
int i;
char username[30][100];
for(i = 0; i < 30; i++)
{
scanf("%s",username[i]);
}
保存在具有稍後釋放的指針。
這將讀取30個字符串到您的用戶名數組中。
如果你想剛纔讀一個用戶名:
char username[30] = {0}; // Same as memset, but shorter to write!
scanf("%s", username);
雖然如其他人所說,scanf()的豈不等於最好的功能改爲「用戶生成的輸入」 - 這是罰款的數據,你的程序已經「檢查」了(也就是說,它不包含「有趣的東西」,符合所提供的長度等),並寫入文件[使用fscanf()]。對於用戶輸入,使用fgets()
來讀取一行文本,然後以任何適合從字符串中獲取實際數據的方式進行操作。例如,如果某個用戶名有超過100個字符[或最後一個例子中有30個字符],則字符串將溢出,並且沒有任何好的事情會發生[在非常糟糕的情況下,您將不會注意到很久以後,這使得它很難調試 - 如果你很幸運,它會立即崩潰]。
非常合理的建議,特別是擺脫'malloc()'。 – DevSolar
我有一個溫和的過敏到「malloc」,所以我儘量避免它,如果可能...;) –
char* username[30];
memset(username,0x00,30);
scanf("%s",&username);
上面的代碼將會崩潰,因爲您正在嘗試輸入指向未分配內存的指針。所以首先你爲指針分配內存,然後讀入內存位置。
char *username[30]
這是一個指針數組字符..
去char username[30]
你到底想幹什麼? – chris
不考慮語法問題,'scanf()'很難適用於任何*除了讀取之前由您自己的程序寫入的數據。可能甚至沒有,因爲'scanf()'提供的錯誤處理很差。 – DevSolar