[英]Trying to reverse a string without using string.h library functions in C using pointers
It returns halfway and shows--Process returned -1073741819 (0xC0000005) This code shows no error or warning also.它中途返回并显示--进程返回 -1073741819 (0xC0000005) 此代码也没有显示错误或警告。 Just want to know exactly why is it happening?
只是想确切地知道为什么会这样?
#include<stdio.h>
void reverse(char*);
int main()
{
char str[200];
printf("Enter a string : ");
scanf("%s",&str);
reverse(str);
printf("Reversed string : %s",str);
}
void reverse(char *p)
{
char temp,*q;
*p=*q;
while(*p!='\0')
{
q++;
}
while(p<q)
{
temp=*p;
*p=*q;
*q=temp;
p++;
q--;
}
}
You never initialized q.您从未初始化 q。 It is pointing to something completely random.
它指向完全随机的东西。
Fix is char temp, *q = p;
修复是
char temp, *q = p;
Did the following changes as answered and added a change also which made the code work.是否按照回答进行了以下更改,并添加了一个使代码正常工作的更改。
#include<stdio.h>
void reverse(char*);
void main()
{
char str[20];
printf("Enter a string : ");
scanf("%s",&str);
reverse(str);
printf("Reversed string : %s",str);
}
void reverse(char *p)
{
char temp,*q=p;
while(*q!='\0')
{
q++;
}
q--;
while(p<q)
{
temp=*p;
*p=*q;
*q=temp;
p++;
q--;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.