Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

C language structure is not woking properly in my code

please take a look at the code below.

 #include <stdio.h>
    #include <conio.h>
    
    struct str {
        char st[1];
        char rule[20];
    } production_rules[30];
    
    int main () {
        int n;
        printf("Enter number of productions: ");
        scanf("%d", &n);
        printf("Enter the productions
");
        for (int i = 0; i < n; i++) {
            printf("Enter the non terminal: ");
            scanf("%s", production_rules[i].st);
            printf("Enter the RHS of the production Rule: ");
            scanf("%s", production_rules[i].rule);
        }
        printf("the production rules are 
");
        for (int i = 0; i < n; i++) {
            printf("%s -> %s
", production_rules[i].st, production_rules[i].rule);
        }
        return 0;
    }

I am getting the following output

Enter number of productions: 1
Enter the productions
Enter the non terminal: A
Enter the RHS of the production Rule: abc
the production rules are
Aabc -> abc

Expected Output:

Enter number of productions: 1
Enter the productions
Enter the non terminal: A
Enter the RHS of the production Rule: abc
the production rules are
A -> abc

The problem is in the last line of the output. I don't understand why the char array is being concatenated. Can some one help me with this problem

question from:https://stackoverflow.com/questions/66058618/c-language-structure-is-not-woking-properly-in-my-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is no issue in your struct, but just the way you use printf, as you put %s to print the element "st", whilst you should use "%c" instead.
In fact, "st" is just a char[1], not a proper string, so it doesn't contain the string termination character ''.
As your struct is stored in memory as a buffer of consecutive char, the "%s" makes the "printf" stop when the termination string character is found, so at the end of the element "rule", and that's reason of your output.

So, just replace %s with %c when printf of st and it will work. Your code should appear like this:

for (int i = 0; i < n; i++) {
        printf("%c -> %s
", production_rules[i].st, production_rules[i].rule);
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...