求助:在C语言中反转字符串时遭遇Segmentation Fault(段错误)
Hey there! Let's walk through the issues in your code that's causing the segmentation fault and get your string reversal working properly.
First: The Root Cause of the Segmentation Fault
In your main function, you're passing a string literal ("ABCDE") to my_revstr. String literals in C are stored in read-only memory sections—any attempt to modify them (which your function tries to do) triggers undefined behavior, and a segmentation fault is a common result here.
To fix this, you need to pass a modifiable character array instead:
int main() { char str[] = "ABCDE"; // This creates a writable array containing the string my_revstr(str); }
Second: Broken Logic in my_revstr
Your current reversal logic is incorrect and contributes to the crash too. Let's break down what's wrong:
ptr += ptr[i]: This is invalid pointer arithmetic—you're adding the ASCII value of the character atptr[i]to the pointer, which sends it flying to an arbitrary memory address (hence the segfault).str[i] = str[(len/2)-1]: This doesn't swap characters; it's just overwriting the i-th character with the middle character of the string, which isn't what reversal does.
Correct Reversal Logic
The standard approach for reversing a string is to swap characters from the start and end of the string, moving towards the center. Here's how to fix my_revstr:
void my_revstr(char str[]) { int len = my_strlen(str); char temp; // Use two indices: one starting at the beginning, one at the end for (int i = 0, j = len - 1; i < j; i++, j--) { // Swap str[i] and str[j] temp = str[i]; str[i] = str[j]; str[j] = temp; } printf("%s\n", str); // Add newline for cleaner output }
How This Works
istarts at 0 (first character),jstarts atlen-1(last character, since strings are 0-indexed).- We swap the characters at these positions, then increment
iand decrementj. - We stop when
i >= j—this means we've swapped all pairs and reached the middle of the string.
Full Corrected Code
Putting it all together, here's the working version:
#include <stdio.h> int my_strlen(char const str[]){ int i = 0; int count = 0; while (str[i] != '\0'){ count++; i++; } return count; } void my_revstr(char str[]) { int len = my_strlen(str); char temp; for (int i = 0, j = len - 1; i < j; i++, j--) { temp = str[i]; str[i] = str[j]; str[j] = temp; } printf("%s\n", str); } int main() { char str[] = "ABCDE"; my_revstr(str); }
This will output EDCBA as expected, with no segmentation faults.
内容的提问来源于stack exchange,提问作者TheTricky65

