运行此代码后,我收到了Access违规。有人可以帮忙吗? [英] I am getting Access violation after running this code. Can anyone help?

查看:80
本文介绍了运行此代码后,我收到了Access违规。有人可以帮忙吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int GetLength(const char* string)
{
  int iLength;
  for(iLength = 0; (*(string + iLength) != '\0'); iLength++)
    ;
  return iLength;
}
void Reverse(char* string)
{
  int iLength = GetLength(string);
  char* pTemp = new char[iLength+1];
  memcpy(pTemp, string, iLength+1);
  for(int i = 0; i < iLength; i++)
  {
    *(string+i) = *(pTemp + iLength - i -1);//Access violation in first iteration
  }
  *(pTemp+iLength) = '\0';
  delete []pTemp;
  pTemp == NULL;
}

推荐答案

string t = string ( t.rbegin(), t.rend() );





string()是一个字符串构造函数,它创建一个新的字符串对象(字符串定义 [ ^ ])



rbegin和rend是反向迭代器,迭代器是一个类似的对象指针的方式(反向迭代器链接 [ ^ ]

rbegin link [ ^ ])





string(tekst.rbegin(),tekst.rend())创建一个字符串,从开头到反转't'



如果这有帮助,请花时间接受解决方案。谢谢。



string ( ) is the string constructor which creates a new string object ( String definition[^] )

rbegin and rend are reverse iterators, an iterator is an object which acts in a similar way to a pointer ( Reverse iterator link[^]
rbegin link[^] )


string ( tekst.rbegin(), tekst.rend() ) creates a string from the beginning to the of the reversed 't'

If this helps please take time to accept the solution. Thank you.


您发布的代码有效,前提是您传递给的字符串Reverse()实际上是一个以0结尾的字符串!您应该至少测试字符串对nullptr,因为这几乎是导致访问冲突的唯一因素:

The code you posted works, provided the string you pass to Reverse() is really a 0-terminated string! You should at the very least test string against nullptr, because that's pretty much the only thing that could cause an access violation:
void Reverse (char* string) {
   if (string == nullptr)
      return;
   ...
}





如果不是它(或者即使它是!),请学习使用调试器,在获得访问冲突的地方中断,并检查变量的当前值。



If that's not it (or even if it is!), learn to use a debugger, break at the point where you get the access violation, and check the current values of your variables.


事实上,我不应该为您提供任何解决方案。但是你可以做的就是这么简单:

As a matter of fact, I should not offer you any solution. But here is the thing you can do, very simple:
for(i=0;i<len;i++) 
{
 swap(str+i, str-i);// you should write the swap function or related code and also figure out how it works 
}





并试着了解斯蒂芬朗所说的话



And also try to understand what stephan lang have said


这篇关于运行此代码后,我收到了Access违规。有人可以帮忙吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆