使用您的 ID(5 位數字)初始化 char 型別的全域一維陣列“StudentData”。在這部分中必須使用指標語法。你能給我一些關于這樣做的提示嗎?
我試過這樣做,
char *StudentData;
void loadData(){
StudentData=(char*)"60897";
}
是對的還是我應該嘗試做其他事情?
uj5u.com熱心網友回復:
您可能想要以下內容:
#include <string.h> //This header has strcpy()
#define ENOUGH_DIGITS 5 //This is so you can easily modify ID length in the future
char StudentData[ENOUGH_DIGITS 1]; //Global array 1 bigger than the longest string
void loadData(){
//Ask the compiler to put a read-only string somewhere in the data memory
const char *myID = "60897";
//Copy the read-only string into the global array
strcpy(StudentData,myID);
}
uj5u.com熱心網友回復:
雖然您確實在使用一個陣列(字串文字實際上是一個),但它是一個匿名陣列——而您studentData只是一個指向該陣列的指標。
一個全域一維陣列“StudentData”
我寧愿將其解釋為您打算擁有一個具有該名稱的真實陣列,因此看起來像:
char studentData[N];
whereN是一個常量運算式,表示陣列的適當大小,至少 5 個,因為您需要能夠存盤 5 個數字 - 如果您的 ID 應該表示為 C 字串,則可能為 6 個(這樣的一個需要一個額外的字符來保存必需的空終止符!),或者您立即使用 2 的冪(最少為 8)。
在這部分中必須使用指標語法。
所以你需要一個指向該陣列的指標:
char* ptr = studentData;
您現在可以只使用指標將值分配給:
*ptr = '0'; // dereferences the pointer, assigns a value to (in this
// case a character representing the digit zero) and
// increments it afterwards to point to the next character
// repeat this for the next four digits!
*ptr = 0; // terminating null character (note: no single quotes)
// or:
*ptr = 0;
// it's up to you to decide if incrementing yet another time actually
// is meaningful (first variant) or unnecessary (second variant)...
如果沒有進一步的要求,您可能會直接在main函式中使用此代碼,或者將其放在另一個被呼叫的函式中,main例如:
void loadData(size_t size, char data[size])
{
// ideally size check with appropriate error handling
// assignment as above
}
// in main:
loadData(sizeof(studentData), studentData);
注:函式的引數全部char* data,char data[]或者char[someArbitrarySize]是等價的,如果任何給定大小,它會被忽略-我們仍然可以將其添加為檔案的目的,在上面簽名:告訴一個大小的陣列(至少)size是預期的。還要注意,如果給定的維度不止一個,這僅適用于最外面的維度!
uj5u.com熱心網友回復:
一維陣列“StudentData”
不不不。StudentData不是一個陣列,它是一個指標。陣列是記憶體塊,而指標是指向記憶體的地址,可能是也可能不是陣列。陣列有時會變成指標,這稱為衰變。
"60897"已經是char *兼容了。您可以直接將其分配給StudentData. 像這樣:
StudentData = "60897";
如果要使用陣列,請執行以下操作:
#include <string.h>
char StudentData[WHATEVER_IS_ENOUGH_TO_HOLD_THE_DATA]; /* allocate array.
make sure that the size of the array accounts for the null
terminating character. */
void loadData(){
strcpy(StudentData, "60897"); //you can't directly assign to an array.
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/384318.html
下一篇:Unity、C#、指標解決方法?
