我盯着这段代码已经有一段时间了,但我无法找出这段代码有什么问题以及如何解决。我认为其中一个数组是在分配的内容之后写入的。
调试器允许我编译,但是当我这样做时,我得到:
Unhandled exception at 0x774615de in HW6_StringProcessing.exe: 0xC0000005: Access violation.
这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STR_SIZE 100
void convertToPigLatin (char * strPtr, char * pStrPtr);
int main(int argc, char *argv[])
{
char str[MAX_STR_SIZE];
char pStr[MAX_STR_SIZE];
FILE *fileInPtr; //Create file name
FILE *fileOutPtr;
fileInPtr = fopen("pigLatinIn.txt", "r"); //Assign text to file
fileOutPtr = fopen("pigLatinOut.txt", "w");
if(fileInPtr == NULL) //Check if file exists
{
printf("Failed");
exit(-1);
}
fprintf(fileOutPtr, "English Word\t\t\t\tPig Latin Word\n");
fprintf(fileOutPtr, "---------------\t\t\t\t----------------\n");
while(!feof(fileInPtr)) //Cycles until end of text
{
fscanf(fileInPtr, "%99s", str); //Assigns word to *char
str[99] = '\0'; //Optional: Whole line
convertToPigLatin(str, pStr);
//fprintf(fileOutPtr, "%15s\t\t\t\t%15p\n", str, pStr);
printf("%s\n", str);
}
system("pause");
}
void convertToPigLatin (const char * strPtr, char * pStrPtr)
{
int VowelDetect = 0;
int LoopCounter = 0;
int consonantCounter = 0;
char cStr[MAX_STR_SIZE] = {'\0'};
char dStr[] = {'-','\0'};
char ayStr[] = {'a','y','\0'};
char wayStr[] = {'w','a','y','\0'};
while (*strPtr != '\0')
{
if (*strPtr == 'a' || *strPtr == 'e' ||
*strPtr == 'i' || *strPtr == 'o' ||
*strPtr == 'u' || VowelDetect ==1)
{
strncat(pStrPtr, strPtr, 1);
VowelDetect = 1;
}
else
{
strncat(cStr, strPtr, 1);
consonantCounter++;
}
*strPtr++;
}
strcat(pStrPtr, dStr);
if (consonantCounter == 0)
{
strcat(pStrPtr, wayStr);
}
else
{
strcat(cStr,ayStr);
strcat(pStrPtr, cStr);
}
printf("%s\n", pStrPtr);
}
最佳答案
我认为问题可能是在尚未初始化的缓冲区中使用strcat()
和strncat()
。调用convertToPigLatin()
之前,请确保使用pStr[]
或其他类似的方法对memset()
进行组合:
while(!feof(fileInPtr)) {
...
str[99] = '\0';
pStr[0] = '\0'; // or memset(pStr, 0, sizeof(pStr));
convertToPigLatin(str, pStr);
...
}
关于c - 指针和字符串处理错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17850095/