0

I'm extremely new to Ubuntu and PuTTY and putting a C++ file into it, but I'm having a problem with my C++ file. What I need the program to do is take a string entered from the Ubuntu side, put into the C++ program, and have it count how many strings are entered in and it sends back like so:

./myfile Supplying arguments now
Argument #0: ./myfile
Argument #1: Supplying
Argument #2: arguments
Argument #3: now
Number of arguments printed: 4

So, when I run my program down below, the program goes on forever and I can't step through it. What is causing it and why and/or what can I do to fix the problem?

#include <stdio.h>
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
    int count = 0;
    while (*argv[argc] != NULL)
    {
        count++;
    }
    cout << count << endl;
    system("PAUSE");
    return 0;
}
  • 1
    `argc` is never changing, so you're always looming at the same member of `argv`. Pay close attention to the code your write. – Jonathon Reinhart Jan 16 '15 at 14:36
  • Also, use something like getc instead of calling pause via system. – Jonathon Reinhart Jan 16 '15 at 14:37
  • 2
    I don't see how "GIT" plays into this. Ubuntu and PuTTY are also not relevant to this question. Apart from that: Did you want do use *argv[ count ]? Did you want to use while( count < argc )? – Andreas Jan 16 '15 at 14:40

1 Answers1

1

Your code is an infinite loop because your while loop always checks the same condition. That's because argc never changes in your code.

What you meant to write is while (*argv[count] != NULL). However, what you meant isn't correct either.

  1. C doesn't check array boundaries. When you read past an array boundary, you will not necessarily encounter a 0 value. You will read random garbage data which is in memory at that place.
  2. You don't need to count the number of arguments yourself, because you already have it in the variable argc.

So a better solution to iterate all the command line arguments would be a for loop which increments count from 0 to argc.

Community
  • 1
  • 1
Philipp
  • 67,764
  • 9
  • 118
  • 153
  • Perfect, I can see where I went wrong, I couldn't step through the program which really made this a headache. Thanks a million! – justyournormalguy13 Jan 16 '15 at 15:40
  • I'm fairly certain that `argv[]` itself is NULL-terminated, as well - i.e. `argv[argc] == NULL`. Not sure if that's a C standard thing, or Sus, POSIX, or something else, though, and I don't have the various documents handy to dig it out. Maybe it's not universally true... – twalberg Jan 16 '15 at 16:19