搅拌长度计算 [英] Stirng Length Calculation
本文介绍了搅拌长度计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在visual studio 2008中使用此代码计算字符串长度,代码为
I want to calculate string length using this code in visual studio 2008,the code is
void main(){
char *str;
int count = 0,i;
printf("\nEnter the String: ");
gets(str);
for(i=0;str[i]!='\0';i++){
count++;
}
printf("\nThe length of the string is %d.",count);
getch();
}
但我收到错误
but I am getting error
"Unhandled exception at 0x6a4794af (msvcr90d.dll) : 0xC0000005: Access violation writing location 0x013f575d."
如何解决请帮助
[更新]
How to solve please help
[Updated]
void main(){
char *str="";
int count = 0,i;
printf("\nEnter the String: ");
gets(str);
for(i=0;str[i]!='\0';i++){
count++;
}
printf("\nThe length of the string is %d.",count);
getch();
}
但是它给出了同样的错误请帮助
but it giving same error please help
推荐答案
你要去找一个未初始化的指针。因此尝试将其输出写入一些奇怪的内存位置。这就是访问违规的来源。
为您要读取的行分配缓冲区并传递该缓冲区以获取,例如:
You are passing to gets an uninitialized pointer. So gets tries to write its output to some weird memory location. That''s what the "Access violataion" comes from.
Allocate a buffer for the line that you want to read and pass that buffer to gets, for example:
char lineBuffer[200];
gets (lineBuffer);
正如您在C ++中获得更高级时的一个注释:有更好的方法来读取一行而不是获取。得到的缺点是你不能告诉它,你的缓冲区有多长;如果你的输入足够长,它会覆盖缓冲区结束并破坏你的记忆。
Just as a note for the time when you are getting more advanced in C++: There are better ways to read a line than gets. gets has the disadvantage that you can''t tell it, how long your buffer is; and if your input is long enough it therefore overwrites the buffer end and corrupts your memory.
这是因为你声明和使用 str <的方式/ code> - 您的代码中没有分配内存。
请参阅此处的示例cplusplus.com参考 [ ^ ]对于一种方法,但你最好使用fgets看看
这篇文章 [ ^ ]使用该建议
It''s because of the way you are declaring and usingstr
- there is no memory allocated to it in your code.
See the example here cplusplus.com reference[^] for one way of doing it but you would be better off using fgets see
this post [^] for a suggestion using that
看起来你正在传递一个未初始化的指针获取
。
尝试更换生产线
char * str;
with
char str [81]; // 80个字符的空间+''\ 0''
看看这是否能让你更进一步。
It looks like you''re passing an uninitialized pointer togets
.
Try replacing the line
char* str;
with
char str[ 81 ]; //room for 80 chars + ''\0''
See if this gets you any further.
这篇关于搅拌长度计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文