4

So I have the following code:

void main(int argc, char **argv)
{
    int loggedIn=0;
    char *currentCommand;

    while (!loggedIn)
    {
    printf("Enter your command:");
    scanf("%s",currentCommand);
    printf("\n%s\n",currentCommand);
    }
}

The problem is scanf() works well the first time, then is starts reading (null) and the output would be Enter your command: (null) in an infinite loop.

I want to input more commands and stop when I change the value of loggedIn, but once I input one command, it starts printing Enter your command: (null) endlesly.

2
  • 1
    You have not allocated any space for currentCommand Commented Oct 30, 2016 at 11:22
  • Yes, it works now. Thanks! Commented Oct 30, 2016 at 11:27

3 Answers 3

3

You need to allocate memory to the currentCommand pointer with malloc (and free it at the end) or give a size to it in the beginning, like

char currentCommand[256];
Sign up to request clarification or add additional context in comments.

1 Comment

Works now. Thanks!
0

currentCommand is pointer variable who will save address(which is integer) of char type variable and have a size of 4 bytes (32 bit machine).

Now when you write ℅s in scanf you are supposed to pass address of char array.(which you haven't declared), so scanf will take the address (value saved in currentCommand which is garbage).

Comments

0

The most important thing while using character pointers is you can create a character array at the time of declaration i.e.,

char *p="Hello World";

This creates memory in data/code section which is read only section.

And you cannot create a character array with scanf() function. Should have to use dynamic memory allocation or initialize as above

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.