简体   繁体   English

C字符串段错误

[英]C strings Seg Fault

I am writing a function that sorts enfrobbed data without converting the entire string back to normal. 我正在编写一个函数,可以对加密的数据进行排序,而无需将整个字符串都转换回正常值。 It passes every test case except for when the two strings are equal, when I get a seg-fault every time. 它通过了每个测试用例,除了两个字符串相等时,而且每次都出现段错误时。 I cannot figure out why I get a bad memory access in this case, as I shouldn't be out of the range of the string. 我不知道为什么在这种情况下我会得到错误的内存访问,因为我不应该超出字符串范围。 Note that the end of the string is expected to be a SPACE, and not a null byte. 请注意,字符串的结尾应为SPACE,而不是空字节。

int i = 0;
for(; a[i] != " " && b[i] != " "; i++)
{
   char axor = a[i] ^ '*';
   char bxor = b[i] ^ '*';
   //printf("A: %i B: %i \n", axor, bxor);                                         
   if (axor < bxor)
     return -1;                             
   if (axor > bxor)
     return 1;
}
if (a[i] == " " && b[i] == " ") //a and b are equal                                                   
  return 0;
if (a[i] == " ")                   
  return -1;
else //a is greater than b                                                                            
  return 1;

Note that a and b are of type char const* Passing in a = b = "aa", for example, results in a segfault 请注意,a和b属于char const *类型,例如,传入a = b =“ aa”会导致段错误

" " is a char[2] . " "是一个char[2] To get a character, use ' ' . 要获取字符,请使用' '

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM