为什么我在C语言上获得了非常巨大的printf输出?

为什么我在C语言上获得了非常巨大的printf输出?,c,C,这是我的代码,我想计算机器人和怪物之间的距离,但输出的水平和垂直是假的 #include <stdio.h> void findPos(char *dir, int a, int b) { int up = 0, down = 0; int left = 0, right = 0; int i,x,y; for (i = 0; dir[i] != '\0' ; i++) { //Counts each direction

这是我的代码,我想计算机器人和怪物之间的距离,但输出的水平和垂直是假的

#include <stdio.h> 

void findPos(char *dir, int a, int b)
{
    int up = 0, down = 0;
    int left = 0, right = 0;
    int i,x,y;

    for (i = 0; dir[i] != '\0' ; i++) {
        //Counts each direction
        if (dir[i] == 'U' || dir[i] == 'u')
            up++;
        else if (dir[i] == 'D' || dir[i] == 'd')
            down++;
        else if (dir[i] == 'L' || dir[i] == 'l')
            left++;
        else if (dir[i] == 'R' || dir[i] == 'r')
            right++;

          //In case of illegal character in the string
        else
        {
            printf("Position Unable to Find, Enter Correct Direction.");
            break;
        }
    }

    //Final position of robot
    x = right - left;
    y = up - down;

    printf("Final Position of the Robot: (");
    printf("%d", x);
    printf(",%d", y);
    print(")");

    printf("\nposition between robot and monster");
    printf("\nhorizontal: %d", a-x);
    printf("\nvertikal: %d", b-y);

}

int main()
{
    char *dir;
    int a,b,t;

    /* Intializes random number generator */
    srand((unsigned) time(&t));

    /* Print 2 random numbers from 0 to 100 */
    a = rand() % 100;
    b = rand() % 100;

    printf("\nCoordinate of monster: ");
    printf("(%d,", a);
    printf("%d)", b);
    //Input the direction string
    printf("\nEnter the Direction String: ");
    scanf("%s", &dir);
    //Function call to calculate position
    findPos(&dir, a,b);

    return 0;
}

看起来您的程序表现出未定义的行为,实际上您很幸运它没有崩溃,dir从未分配。您可能希望在使用之前调用它,并删除&in scanf,infact move to fgets,除非倾向于使用scanf


将printf语句添加到检查变量a、b、x和y的代码中。确保这些值是合理的。dir是一个永远不会指向任何有效位置的指针。即使dir指向某个合理的位置,findPos也会收到一个指向它的指针,它完全指向其他位置。它已经是char*,不要&它。这通常会生成至少一些警告,您是在启用警告的情况下编译的,对吗?为了澄清@pmg的评论,您需要char dir[2048];扫描%2047s,直达;或类似的。其他人说:请启用警告通常-墙或/墙。然后修复这些警告:包括srand和time。如果没有将指向正确类型的指针传递给time,最好使用timeNULL。
Coordinate of monster: (5,47)  
Enter the Direction String: UURRRRRLLL
Final Position of the Robot: (2,2)  
position between robot and monster  
horizontal: 19530  
vertikal: 1280463440
   printf("\nEnter the Direction String: ");
        scanf("%s", dir);