-1

C code:

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

#define STRINGS 10
#define STR_LEN 20

int main(void)
{
    char words[STRINGS][STR_LEN];

    char input[STR_LEN];

    int i;
    int mycount;

    for(i = 0;i < STRINGS;++i;)
    {
        printf("Enter a word (or 0 to quit)\n:");

        scanf("%19s", input);

        if(input[0] == '0') break;

        strncpy(words[i], input, STR_LEN);

        mycount++;
    }

    printf("A total of %d strings were entered!\n",mycount);

}

problem: When I run this code and enter some strings it doesn't print out the amount of strings I entered

enter image description here

TechDinoKing
  • 51
  • 1
  • 8
  • 2
    `for(i = 0;i < STRINGS;++i;)` doesn't compile. BTW `i` and `mycount` are the same, except for the fact that `mycount` was never initialized. – joop Mar 13 '17 at 15:07
  • 3
    you forgot to initialize `mycount` to zero – Ankur Jyoti Phukan Mar 13 '17 at 15:08
  • 2
    Just a hint: Finding an obvious error in the C standard library of a major implementation would not be unheard of, but it is extremely unlikely. This stuff is 20 or 30 years old. Comparatively unlikely to finding a compiler error, or a CPU bug. I suppose most of us suspected one or the other at some point, but it was almost never true. Like, I had a colleague around 1997 who *did* find a bug in a Z80 clone. That unlikely. In all other instances the error was a more or less subtle coding error, or an error in the build environment setup. – Peter - Reinstate Monica Mar 13 '17 at 15:14
  • 1
    Don't use `strncpy`, it is a dangerous function and was never intended to be used for null terminated strings, [see this](http://stackoverflow.com/questions/2114896/why-are-strlcpy-and-strlcat-considered-insecure). – Lundin Mar 13 '17 at 15:25

2 Answers2

10

You need to initalize mycount to 0.

int mycount =0;
lakeIn231
  • 1,177
  • 3
  • 14
  • 34
  • Please at least make the OP provide critical information in text, rather than images. – Nic Mar 13 '17 at 17:26
3

The variable mycount is uninitialized. You then attempt to modify it in the for loop via the ++ operator. So you're reading garbage values and writing garbage values. This explains the output you're getting.

Reading an uninitialized variable invokes undefined behavior. In this case, it manifests as garbage values, but it could just as easily output the expected value or cause a crash.

Initialize this variable at the time it is declared.

int mycount = 0;
dbush
  • 205,898
  • 23
  • 218
  • 273