Compilation error in C language (pointer usage is not good...?)

Asked 2 years ago, Updated 2 years ago, 36 views

Always I am indebted.
Ruby was able to output as expected, but it doesn't work out as expected in C language.


Created in Ruby and C language. I am attaching it as follows, so please check it.
-------------------------
■Problems
setup ia...Insert the value a into the variable i (i=1,2)
addition a... Calculate the value +a of variable 1 and substitute the calculation result to variable 2
subtract a... Calculate the value of variable 1 -a and substitute the calculation result to variable 2

■Example Input
4
setup120
setup240
addition40
subtract-20

■Expected output example
20
40
-----------------------------------------------------------------------------------------------

Ruby

t=gets.to_i

a = 0,0

US>t.times{
    aary=gets.chomp.split('')
        ifary[0] == "setup"
            s=ary[1].to_i
            n=ary[2].to_i
            a[s-1] = n
        elsifary[0] == "addition"
           x =ary[1].to_i
           a[1] = a[0] + x 
        elsifary[0] == "subtract"
            y=ary[1].to_i
            a[1] = a[0]-y 
        end
}
puts a.join('')


C

#include<stdio.h>
# include <string.h>

int main(void){

    charary [3];
    inta[2];
    chat;
    scanf("%s", & t);

    for(int j=0;j<t;j++){
        if(strcmp(t, "setup")==0){
            ints=ary[1];
            int n =ary[2];
            n = a[s-1];
        } 
        else if(strcmp(t, "addition")==0){
            intx =ary[1];
            a[1] = (a[0]+x);
        } 
        else if(strcmp(t, "subtract")==0){
            inty=ary[1];
            a[1] = (a[0]-y);
        }
    }
    printf("%d\n", a);
    return 0;
}

ruby c

2022-09-30 14:32

1 Answers

It's not an answer, but it's too long to write in the comment section, so I'll use the answer section.
The big mistake is 3 points.

does not actually have a string type ( to handle strings.Present source is misleading and needs to be corrected as if the "pointer to char" type is a string (array and pointer can be used in the same way, but completely different).The size of the array is determined at the time of array definition, or rather, it is a specification that must be determined, so it is not easy to "read any length of string" (the number of characters dynamically changes at the time of execution).Therefore, you can only read a string of up to N characters (or use dynamic memory to handle arbitrary length strings).

Furthermore, when


© 2024 OneMinuteCode. All rights reserved.