访问违反写入位置(visual studio 2008)基于指针的代码
Access violating writing location (visual studio 2008) Code based on pointers
主要问题是sem->i = a;当调用yylex并且c是alphaSem ->s[i] = c;不能工作,因为sem->s[i]指向的地址有问题。
更多细节:所以我要做的是打开一个文本文件,读它里面的内容,直到文件的末尾。如果它是一个字母数字(例如:hello,example2 hello45a)在函数yylex中,我将每个字符放入数组(sem->s[i]),直到我找到文件的结尾或不是字母数字的东西。如果在yylex函数处是一个数字(例如:5234254 example2: 5),则将每个字符放入数组arithmoi[]中。在with attoi之后,我将数字放入到sem-> I中。如果我在yylex中删除else If (isdigit(c))部分,它会工作(如果txt中的每个单词都不是以数字开头)。不管怎么说,当它只找到以字符开头的单词时,效果很好。然后,如果它找到数字(它使用elseif(isdigit(c)部分)它仍然工作…直到它找到一个以字符开头的单词。当这种情况发生时,有一个访问违反写入位置,问题似乎是我有一个箭头。如果你能帮助我,我将非常感激。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <iostream>
using namespace std;
union SEMANTIC_INFO
{
int i;
char *s;
};
int yylex(FILE *fpointer, SEMANTIC_INFO *sem)
{
char c;
int i=0;
int j=0;
c = fgetc (fpointer);
while(c != EOF)
{
if(isalpha(c))
{
do
{
sem->s[i] = c;//the problem is here... <-------------------
c = fgetc(fpointer);
i++;
}while(isalnum(c));
return 1;
}
else if(isdigit(c))
{
char arithmoi[20];
do
{
arithmoi[j] = c;
j++;
c = fgetc(fpointer);
}while(isdigit(c));
sem->i = atoi(arithmoi); //when this is used the sem->s[i] in if(isalpha) doesn't work
return 2;
}
}
cout << "end of file" << endl;
return 0;
}
int main()
{
int i,k;
char c[20];
int counter1 = 0;
int counter2 = 0;
for(i=0; i < 20; i++)
{
c[i] = ' ';
}
SEMANTIC_INFO sematic;
SEMANTIC_INFO *sema = &sematic;
sematic.s = c;
FILE *pFile;
pFile = fopen ("piri.txt", "r");
do
{
k = yylex( pFile, sema);
if(k == 1)
{
counter1++;
cout << "it's type is alfanumeric and it's: ";
for(i=0; i<20; i++)
{
cout << sematic.s[i] << " " ;
}
cout <<endl;
for(i=0; i < 20; i++)
{
c[i] = ' ';
}
}
else if(k==2)
{
counter2++;
cout << "it's type is digit and it's: "<< sematic.i << endl;
}
}while(k != 0);
cout<<"the alfanumeric are : " << counter1 << endl;
cout<<"the digits are: " << counter2 << endl;
fclose (pFile);
system("pause");
return 0;
}
main
中的这一行正在创建一个未初始化的 SEMANTIC_INFO
SEMANTIC_INFO sematic;
整数sematic.i
的值为unknown。
指针sematic.s
的值未知。
然后尝试写入sematic.s[0]
。您希望sematic.s
指向足以容纳该文件内容的可写内存,但是您没有让它指向任何东西。
相关文章:
- c++r值引用应用于函数指针
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何防止C++遗留代码中的挂起指针
- 理解这行C++指针代码
- 如何修复我的最大公约数代码?它适用于除零和零以外的所有数字
- 为什么我们不在下面给出的代码中使用指针来实例化C++的实体对象?
- 为什么我的代码在指针方面停止运行?
- 以下与指针相关的代码的输出是什么?
- 请找出我的代码中的错误,它在提交得到错误答案的同时仍然适用于我的所有测试用例
- 是否有一种 STL 算法可以最后找到,但它也适用于指针?
- std::sort / 适用于测试代码,但无法推断出模板
- 动态强制转换适用于模板成员函数内的共享指针和弱指针,无需代码重复
- 我的指针代码 c++ 中的分段错误(核心转储)
- 这两个指针代码有什么区别
- 由于没有明显的原因,请继续在C 的指针代码上遇到错误
- C++:传递和返回指向数组的指针-代码不起作用
- C++相当于 Python 代码:'function(*list)'
- Int 值奇怪地类似于指针
- 如何将 Visual Studio 配置为在调试时'skip'智能指针代码?
- 用于检查 R 函数是否依赖于 C/C++ 编译代码的函数