-1

My simple calculator is trying to display the chosen operation of the user. I understand that in C, strings must be declared as 1D char arrays.

int a, b;
int oper; //operation number
char operName[15];

printf("\nEnter two numbers: ");
scanf("%d%d", &a, &b);
printf("\nYou entered: %d and %d", a, b);

printf("\nChoose operation:"
        "\n1 = +"
        "\n2 = -"
        "\n3 = x"
        "\n4 = /");
scanf("%d", &oper);

The code compiles and runs. But when executing the switch block, it stops working. I'm using switch to choose the appropriate operation name, and assign it to operName (so I can display the chosen operation before I do the actual operation).

switch(oper){
    case 1:
        operName == "Addition";
        break;  
    .
    .
    .
    default:
        operName == "Invalid input";
}

printf("\n\nYou chose: %s", oper);

I read somewhere that I need to use pointers to prevent memory leaks, but I'm new to this so maybe there's an easier way.

3
  • If you're trying to assign that string literal into operName , use strcpy(), strncpy(), strlcpy() or memcpy() Commented Apr 14, 2017 at 4:40
  • The statement "... I need to use pointers to prevent memory leaks..." on its own makes no sense; pointers are not some magic mechanism to prevent memory leaks, they are simply memory addresses. Memory leaks are caused by dynamically allocating memory and failing to deallocate it; you are not using dynamic memory allocation (in the code presented), so memory leak is not an issue. Besides dynamic memory allocation requires pointers, so in that sense pointers can cause leaks, not prevent them - but only through incorrect use; correct code prevents (or rather avoids) memory leaks. Commented Apr 14, 2017 at 6:39
  • @Clifford oh my bad for not using the concept well. I'll keep studying to learn more :) Commented Apr 14, 2017 at 9:42

1 Answer 1

0

The == is not for assignment. C is a pretty low level language you can not assign values to strings in C like you would for an integer or a character.

To do so you must use the standard library string.h.

For instance:

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

int main(void)
{
    char source[1000], destination[1000];

    /* Do something with the strings */

    strcpy(destination, source);
    return 0;
}

Find out more about string.h here

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it worked! char operName[15]; /* ... */ strcpy(operName, "ADD");
You are welcome; glade I could be of help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.