我知道這是一個非常簡單的問題,但我是新手,在這里有點兒......我正在學習更多關于如何使用函式的知識,如果它只是在 main 中,我可以讓它作業,或者我可以使用另一個方式,但我正在嘗試使用 strcpy() 解決它,并且我不想更改 main,everythijg 應該在函式中,非常感謝任何幫助。
char swap_char(char *s1, char *s2) {
printf("before swapping : swap_char(\"%s\", \"%s\")\n", s1, s2);
char temp[50];
strcpy(temp, s1);
strcpy(s1, s2);
strcpy(s2, temp);
printf("After swapping : swap_char(\"%s\", \"%s\")\n", s1, s2);
}
main() {
swap_char("please","work");
}
uj5u.com熱心網友回復:
"please"有 7 個字符(包括終止符),但"work"只有 5 個字符。有足夠的空間用于第一個字串包含"work",但第二個字串沒有不有足夠的空間來容納"please"它。您的代碼具有文字字串
"please"和"work",這意味著它們很可能位于只讀記憶體中,并且無法更改或覆寫。
解決這兩個問題我得到:
char swap_char(char *s1, char *s2) {
printf("before swapping : swap_char(\"%s\", \"%s\")\n", s1, s2);
char temp[50];
strcpy(temp, s1);
strcpy(s1, s2);
strcpy(s2, temp);
printf("After swapping : swap_char(\"%s\", \"%s\")\n", s1, s2);
}
int main() {
char alpha[20] = "please"; // Declare space 20: MORE than enough space for either string
char beta[20] = "work"; // Also, use a local array, which is NOT read-only, and can be changed.
swap_char(alpha,beta);
return 0;
}
輸出
Success #stdin #stdout 0s 5524KB
before swapping : swap_char("please", "work")
After swapping : swap_char("work", "please")
uj5u.com熱心網友回復:
第一步是閱讀檔案以了解如何使用它并查看它們是否有任何有用的示例。
這里的第一個問題是我們不知道我們是否有足夠的空間來完成這項任務。相反,我們可以malloc動態間隔以確保我們不會遇到問題。
// We don't need to return a char
void swap_char(char *s1, char *s2) {
printf("before swapping : swap_char(\"%s\", \"%s\")\n", s1, s2);
// Allocate on the heap so we know we will never run out of space on a long input
char temp = malloc(strlen(s1) 1);
strcpy(temp, s1);
strcpy(s1, s2);
strcpy(s2, temp);
// Free temporary buffer
free(temp);
printf("After swapping : swap_char(\"%s\", \"%s\")\n", s1, s2);
}
然而,這里有一個更大的問題。我們不知道兩個指標是否都分配了足夠的記憶體。這就是為什么這種方法不是那么實用的原因。此外,通過直接傳遞字串指標而不是使用指向堆疊或堆上的緩沖區的指標,可能會嘗試改變只讀記憶體。在大多數現代系統上,字串常量與每個函式中的匯編指令一起加載到只讀記憶體中。這很好,因為它可以防止惡意行為者或未定義的行為修改函式程式集。
char *a = "please";
char *b = "work";
// Create new buffers with the required space to use instead
unsigned int buffer_len = imax(strlen(a), strlen(b)) 1;
char *a_buffer = malloc(buffer_len);
char *b_buffer = malloc(buffer_len);
// Copy the input strings into our new buffers
strcpy(a_buffer, a);
strcpy(b_buffer, b);
// Finally swap the buffers
swap_char(a_buffer, b_buffer);
如您所見,這不是很實用,但它是可能的。更實用的方法是只交換變數持有的指標。
void swap_strings(char **s1, char **s2) {
char *temp = *s1;
*s1 = *s2;
*s2 = temp;
}
char *a = "please";
char *b = "work";
printf("Before swapping : swap_char(\"%s\", \"%s\")\n", a, b);
swap_strings(&a, &b);
printf("After swapping : swap_char(\"%s\", \"%s\")\n", a, b);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/370321.html
標籤:C
