Stefan Cvetkovic
Stefan Cvetkovic

Reputation: 144

Strange characters in c

This is my source code:

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

void main()
{
    int broj_znakova,i=0;
    char niz1[81],niz2[81];

    printf("Enter something, for end Ctrl/c \n\n");
    while(fgets(niz1,81,stdin)!=NULL)
    {
        continue;
    }
    printf("You just enter: %s \n",niz1);
    printf("This string is long %d\n",(strlen(niz1)-1));
    strcpy(niz1,niz2);
    printf("niz2 is %s\n",niz2);
    if(strcmp(niz1,niz2)==0)
    {
        printf("niz1 and niz2 is same\n");
    }
    else
    {
        printf("niz1 != niz2\n");
    }
    while(niz1[i]!='\n')
    {
        if(niz1[i]==' ')
        {
            broj_znakova ++;
            i=i+1;
        }
    }
    printf("Spaces in string = %d\n",broj_znakova);
}

When i press Ctrl/c i got a bunch of strange characters, can someone help??? I google something about flushing but i'm new :)

Upvotes: 3

Views: 975

Answers (3)

JMC
JMC

Reputation: 930

On this line

strcpy(niz1,niz2);

I believe your parameters are reverse, it should be strcpy(niz2, niz1); The strange characters you are seeing is because niz2[81] has memory allocated, but it's not "filled in". So you get whatever 'magical' data that allocation may contain. That is, until you put something in it, or do memset, etc.

Upvotes: 0

richardhsu
richardhsu

Reputation: 878

C does not "zero out" information in memory (in general) so when it allocates variables, you get whatever is there in memory at the time (whether it is logically readable as words or not), if you are printing something without the system knowing this is a string then it will keep printing until it encounters a NULL terminating character, if there is none, it tries to print whatever is in memory and this produces the weird characters.

Upvotes: 1

Mark Wilkins
Mark Wilkins

Reputation: 41232

The contents of niz2 is not initialized. It will result in undefined behavior. Perhaps you meant to copy niz1 to niz2. If so, then you need to reverse the parameters in the strcpy call. With strcpy, the first parameter is the target.

Note too that the variable broj_znakova is never initialized.

Upvotes: 1

Related Questions