访问违反写入位置(visual studio 2008)基于指针的代码

Access violating writing location (visual studio 2008) Code based on pointers

本文关键字:于指针 代码 指针 2008 studio visual 位置 访问      更新时间:2023-10-16

主要问题是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指向足以容纳该文件内容的可写内存,但是您没有让它指向任何东西。