0

2 つのポインター変数をグループ化するために を作成したstructので、それらにアドレスを格納できます。main次に、構造体をインスタンス化し、コンテストの 2 つの変数を参照しています。ユーザー出力に基づいて 2 つの文字列を比較し、目的の結果を返します。

コードはこちら

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <ctype.h>

typedef struct
{
    char *name;
    char *name2;
} names;

int main()
{
    names nm;
    printf("Please enter first string: ");
    scanf("%s", nm.name)
    printf("Please enter second string: ");
    scanf("%s", nm.name2);

    if(strcmp(nm.name, nm.name2) == 0)
        printf("Strings %s and %s do match\n", nm.name, nm.name2);  
    else
        printf("Strings %s and %s do not match\n", nm.name, nm.name2);
    return 0;
}

私はしようとした printf("%s", &nm.name);

私は初心者のCユーザーです。ありがとう!

structポインター変数なしで機能する例

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <ctype.h>

int main()
{
    char name[20];
    printf("Please enter first string: ");
    scanf("%s", &name);
    char name2[20];
    printf("Please enter second string: ");
    scanf("%s", &name2);

    if(strcmp(name, name2) == 0)
        printf("Strings %s and %s do match\n", name, name2);    
    else
        printf("Strings %s and %s do not match\n", name, name2);
    return 0;
}




gcc -Wall -Wextra -Wformat -pedantic -o strcmp strcmp.c 

strcmp.c: In function ‘main’:
strcmp.c:10:2: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[20]’ [-Wformat]
strcmp.c:11:2: warning: ISO C90 forbids mixed declarations and code [-pedantic]
strcmp.c:13:2: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[20]’ [-Wformat]
strcmp.c:15:2: warning: implicit declaration of function ‘strcmp’ [-Wimplicit-function-declaration]
4

4 に答える 4

2

編集した質問について、scanf間違って使用しています:

scanf("%s", &name);

する必要があります

scanf("%s", name);

scanfwithを使用した例を見たことがあるはずです&が、この場合、nameは既に であり、関数の引数として渡すとchar [20]に減衰します。char *

于 2013-09-17T11:30:09.460 に答える
1

ポインターが何かを指すようにする必要があります。たとえば、次のようになります。

int main()
{
    char buff1[20];
    char buff2[20];
    names nm;
    nm.name = buff1;
    nm.name2 = buff2;
于 2013-09-17T11:30:18.367 に答える