我已經在這個代碼盯着很長一段時間,我無法找出什麼不對的代碼,以及如何解決它。我認爲其中一個數組正在寫入已分配的數據。指針和字符串處理錯誤
調試器是讓我去編譯,但是當我做,我得到:
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,當你編譯這個你得到了什麼警告? (你有所有的警告開啓,對吧?)嗯 –