简体   繁体   中英

Store a char pointer from terminal input in C

I'm trying to create a simple calculator with input from the terminal. It is supposed to work like this:

./main.c 1 + 3
1 + 3 = 4

It is very simple code per se, but I have a problem with the terminal input. I have read a lot here at stackexchange about terminal input but I get this error while compiling:

error: assignment from incompatible pointer type [-Werror=incompatible-pointer-types]

I do not know why. I have tried a lot of different ways to do it but it does not work. Here is the code, all I want to know is how to store the 1, + and 3 in the example above. The code I post here is just an example as how I can store the most "difficult" operation, in this case the + operator.

#include<stdio.h>

int
main(int argc, char *argv[])
  {

    char operator;
    int *operatorp;
    operatorp = &operator;

    operatorp = argv[2];

    printf("%c\n",operator);

    return 0;
 }

It is not correct, you are trying to convert a int * to a char.

Just do

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

int main(int argc, char **argv)
{
  int nbr1 = atoi(argv[1]);
  char operator = argv[2][0];
  int nbr2 = atoi(argv[3]);

  int result = 0;

  if (operator == '+')
    result = nbr1 + nbr2;
  printf("%d\n", result);
}

argv is a matrix (2d array), that means argv[2] is an array of chars and you must do something like this:

char operator = argv[2][0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM