我已经在这个代码盯着很长一段时间,我无法找出什么不对的代码,以及如何解决它。我认为其中一个数组正在写入已分配的数据。指针和字符串处理错误
调试器是让我去编译,但是当我做,我得到:
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);
}
和......有什么问题,你遇到? – akira
你在哪里初始化pStrPtr?你使用'strncat' ...之前的价值是什么?函数开始时的值是多少? – rabensky
user2525288,当你编译这个你得到了什么警告? (你有所有的警告开启,对吧?)嗯 –