【发布时间】:2016-05-01 10:54:01
【问题描述】:
我不理解这个错误(C2100:非法间接)。我已经在底部附近标记了三个实例。我在网上看过,我知道这与我的指针有关,但是在这 8 个小时之后,我完全迷失了。这里也可能还有其他一些错误,但我什至无法分辨,因为我无法编译它。请帮忙,我希望得到一个我能理解的解释,这样我就可以弄清楚我在未来做错了什么。
// INCLUDE FILES
#include <stdio.h>
#include <string.h>
// PROGRAM CONSTANTS
#define MAX_MSG_LEN 81 // Maximum Message Length (Including /0 Character)
// FUNCTION PROTOTYPES
void printLength(int, int); // Function to Validate & Print Length of String
void printString(int, char); // Function to Print the String in Reverse
void writeToFile(int, char);
// GLOBAL VARIABLES
char input[MAX_MSG_LEN]; // Input String
int maxLength = MAX_MSG_LEN - 1; // Actual String Length (Not Including /0 Character)
char *ptr = input; // Character Pointer to String
int length = 0; // Length of Current String
int lcv = 0; // Loop Control Variable
void main()
{
FILE *ifp;
ifp = fopen("reverseString.txt", "w");
printf("\n\nEnter a String Between 1 and %d Characters: ", maxLength); // Prompts User to Enter a String Less Than 80
gets(input); // Receives the Inputted String from the User
length = strlen(input); // Counts the Length of the Inputted String & Assigns the Number to the "length" Variable
printLength(length, maxLength);
printString(length, *ptr);
writeToFile(length, *ptr);
}
void printLength(int length, int maxLength)
{
if(length > maxLength)
{
printf("\n\nThe Maximum Length of %d Characters was Exceeded!", maxLength);
printf("\nProgram Terminated...\n\n");
exit(0);
}
printf("\n\nThe Length of the Input String was: %d\n", length); // Prints the Length of the Inputted String
}
void printString(int length, char ptr)
{
for(; lcv < length; lcv++)
{
ptr++;
}
length = lcv;
printf("\nThe String in Reverse: ");
for(ptr--; length > 0; length--)
{
printf("%c", *ptr); // HERE IS ONE INSTANCE OF C2100
*ptr--; // HERE IS ONE INSTANCE OF C2100
}
printf("\n\n");
return;
}
void writeToFile(int length, char ptr)
{
FILE *ifp;
ifp = fopen("reverseString.txt", "w");
fprintf(ifp, "%c", *ptr); // HERE IS ONE INSTANCE OF C2100
fclose(ifp);
}
【问题讨论】:
-
当您修复
printString中的错误时,请注意您实际上并不需要第一个循环,您只需执行ptr += length。您也不需要分配给length,因此您不需要全局变量lcv(这很好,应该避免使用全局变量)。 -
您正在从 main 发送 ptr 的内容,基本上是字符串 (
char* ptr)。您的函数将其作为单个字符 (char ptr) 接受,然后您的逻辑尝试在变量 ptr (*ptr) 中获取字符的内容。难怪它失败了。
标签: c pointers function-parameter