-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.

reiallenramos
  • 1,235
  • 2
  • 21
  • 29
  • If you're trying to assign that string literal into operName , use strcpy(), strncpy(), strlcpy() or memcpy() – Rohan Kumar Apr 14 '17 at 04: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. – Clifford Apr 14 '17 at 06:39
  • @Clifford oh my bad for not using the concept well. I'll keep studying to learn more :) – reiallenramos Apr 14 '17 at 09:42

1 Answers1

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

Remy J
  • 709
  • 1
  • 7
  • 18