为什么每次我调用不同的函数时<null>都会终止?

时间:2019-01-04 16:21:00

标签: c arrays function pointers

作为编程的新手,我犯了很多错误,但是我无法理解完美的指针。我编写了一个代码,在其中添加了有关添加食物计划的数据。在使用Modify函数之后,我希望我的代码打印最后添加的数据。但这是问题所在,它每次都会打印出来。您知道该如何解决吗?

int login ( char name[50] );
void autoPass( char username[50] );
char pass[50];
int n = -1; //global counter
char *table[100][4];
void Add( int n );
void Modify( int n );

int main()
{
    char selection[7];
    printf( "\n\nChoose between: Add,Modify,View,Search,Sort,Exit\nSelection: " );
    scanf ( "%s",&selection );

    while ( ( strcmp( selection,"Exit" )  == 0 ) == 0 )
    {
        if (strcmp( selection,"Add" ) == 0 )
        {
            Add( n );
            printf( "Press any character to continue or Exit to finish.\n" );
            scanf ( "%s",&selection );
            printf( "check1" );
        }else if ( strcmp( selection,"Modify" ) == 0 )
        {
            Modify( n );
            printf( "Press any character to continue or Exit to finish.\n" );
            scanf ( "%s", &selection );
            printf( "check2" );
        }
    }
}



void Add (int n)
{
    int i,j;
    n++;
    for ( j = 0 ; j < 4 ; j++ )
    {
        if ( j == 0 )
        {
            printf ( "Enter a food:\n" );
            table[n][j] = (char*) malloc( 30 );
            scanf( "%s",table[n][j] );
        }else if (j == 1 )
        {
            printf("Enter calories:\n");
            table[n][j]=(char*) malloc(30);
            scanf("%s",table[n][j]);
        }else if ( j == 2 )
        {
            printf( "Enter the time you ate:\n" );
            table[n][j] = (char*) malloc( 30 );
            scanf ( "%s",table[n][j] );
        }else if ( j == 3 )
        {
            if (atof( table[n][j-1]) >= 5.00 && atof( table[n][j-1] ) <= 11.59 )
            {
                table[n][j] = "prwino";
            }else if( atof( table[n][j-1] ) >= 12.00 && atof( table[n][j-1] ) <= 19.59 )
            {
                table[n][j] = "mesimeriano";
            }else if ( atof( table[n][j-1] ) >= 20.00 && atof( table[n][j-1] ) <= 4.59 )
            {
                table[n][j] = "vradino";
            }
        }
    }
}

void Modify( int n )
{
    int i,j;
    for ( j=0 ; j < 4 ; j++ )
    {
       printf ( "%s",table[n][j]," " );
     }
     printf( "\n" );
 }

我希望我的Modify函数可以打印我之前使用Add函数添加的数据,而不是每次打印我时都要打印。

1 个答案:

答案 0 :(得分:1)

您的代码似乎有一些问题。

您应该替换所有scanf调用:

scanf ( "%s",&selection );

并通过以下方式更改它们:

scanf ( "%s",selection ); /// Drop the &

您需要删除&,因为格式%s期望使用类型char*的参数,但是当您使用&selection时,该参数变为char (*)[7],而不是char*就像您声明它一样。

您还应该始终检查scanf的返回值:

if ( scanf ( "%6s",selection ) != 1 ) ///notice 6 there?
{
    printf("Error, scanf()\n" );///Is there to read only 6...
    exit( EXIT_FAILURE );
}

另一个问题在void Add ( int n )内部,您在其中递增n

n++;

但是您还声明了n为全局变量: int n = -1; //global counter

您期望哪个n递增?

modify()函数中,您有太多参数:

printf ( "%s",table[n][j]," " );

丢弃最后一个" "

printf ( "%s",table[n][j] );

建议您使用strcasecmp代替strcmp。 您需要为此添加strings.h