C语言中write access violation含义、解决及最长公共前缀代码排查
C语言最长公共前缀函数的写入访问错误问题
我是C语言纯新手,之前用的都是Visual Basic、C#这类不用操心底层细节的语言。最近开始学指针,正在通过LeetCode题目练习。
题目要求:编写函数找出字符串数组中的最长公共前缀,若不存在公共前缀则返回空字符串""。
我的尝试代码:
#include<stdlib.h> #include<stdio.h> #include<string.h> char* longestCommonPrefix(char** strs, int strsSize) { if (strsSize == 1) return strs[0]; if (strs[0] == "") return ""; char* result = strs[0]; size_t result_length = strlen(result) - 1; char* result_end = strs[0] + result_length; for (size_t i = 1; i < strsSize; ++i) { size_t length = strlen(strs[i]) - 1; if (length < 1) return ""; if (length < result_length) { result_end = strs[0] + length; result_length = length; } char* temp1 = result; char* temp2 = strs[i]; while (*temp1 == *temp2 && temp1 < result_end) { ++temp1; ++temp2; } if (temp1 < result_end) { result_end = temp1 - 1; result_length -= strlen(result_end) - 1; } } *(result_end + 1) = '\0'; return result; } int main(int argc, char* argv[]) { char* a[3]; a[0] = "flower"; a[1] = "flight"; a[2] = "flow"; char* b = longestCommonPrefix(a, 3); printf(b); }
为什么在语句*(result_end + 1) = '\0';处会出现write access violation错误?我搜索后了解到C字符串是只读的,想请教具体原因是什么,有什么解决方法?另外也欢迎提供C语言的通用技巧,谢谢。
编辑说明:
感谢@Chris提供的解决方案,以下是修改后可正常运行的代码,同时也融入了@@WeatherVane提供的C语言技巧:
#include<stdlib.h> #include<stdio.h> #include<string.h> char* longestCommonPrefix(char** strs, int strsSize) { if (strsSize == 1) return strs[0]; if (strs[0][0] == 0) return ""; char* result = _strdup(strs[0]); size_t result_length = strlen(result) - 1; char* result_end = strs[0] + result_length; for (size_t i = 1; i < strsSize; ++i) { char* str = _strdup(strs[i]); size_t length = strlen(str) - 1; if (length < 1) return ""; if (length < result_length) { result_end = str + length; result_length = length; } char* temp = result; while (*temp == *str && temp < result_end) { ++temp; ++str; } if (temp < result_end) { result_end = temp - 1; result_length -= strlen(result_end) - 1; } } *(result_end + 1) = '\0'; return result; } int main(int argc, char* argv[]) { char* a[3]; a[0] = "flower"; a[1] = "flight"; a[2] = "flow"; char* b = longestCommonPrefix(a, 3); printf(b); }
内容的提问来源于stack exchange,提问作者OldCrow
相关产品推荐
相关产品推荐

