0 c string reverse segmentation-fault
在编译并运行这个小程序来反转字符串时,我会在任何输出发生之前得到分段错误.请原谅我,如果这是一个显而易见的问题,我对C仍然很新.
#include <stdio.h>
int reverse(char string[], int length);
int main() {
char string[] = "reversed";
printf("String at start of main = %s", string);
reverse(string, sizeof(string));
printf("%s\n", string);
return 0;
}
// Reverse string
int reverse(char string[], int length) {
int i;
char reversed[] = {};
int temp;
for(i = 0; i < length; ++i) {
temp = string[i];
reversed[length - i] = temp;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
因为这:
首先,您创建一个零元素的数组:
char reversed[] = {};
Run Code Online (Sandbox Code Playgroud)
然后你尝试写入超出其范围的数组:
reversed[length - i] = temp;
Run Code Online (Sandbox Code Playgroud)
更新:
以上意味着您需要分配大小仅在运行时已知的内存(它length).通常的C风格方式是......通过将内存分配的负担推给调用者:
int reverse(const char* string, char* destination, int length);
Run Code Online (Sandbox Code Playgroud)
此函数将写入调用者提供的缓冲区,现在还必须确保:
| 归档时间: |
|
| 查看次数: |
349 次 |
| 最近记录: |