how to get rid off garbage in array of chars?

fang_dejavu picture fang_dejavu · Mar 19, 2010 · Viewed 15.4k times · Source

I'm writing a C program but I keep having problems with my array of chars. I keep getting garbage when I print it using prinf. here is an example of what I get when I print it:

char at t.symbol is Aôÿ¿
char at tabl[0].symbol is A
char at tabl[1].symbol is a
char at tabl[2].symbol is a
char at tabl[3].symbol is d
char at tabl[4].symbol is e
char at tabl[5].symbol is f
char at tabl[6].symbol is g
char at tabl[7].symbol is h
char at tabl[8].symbol is i
char at tabl[9].symbol is x
char at t[0].symbol is a0AÃ
char at t[1].symbol is b)@Ã4
char at t[2].symbol is ckU*
char at t[3].symbol is Aôÿ¿
char at t[4].symbol is

could someone tell me how to get rid off the garbage in the array of chars?

here is my code

#define MAX 100
#ifndef SYMBSIZE
 #define SYMBSIZE 1
#endif    

typedef struct tableme 
{
    char symbol[SYMBSIZE];
    int value;
    int casenmbr;
    int otherinfo;
}tabletype;
int main(int argc, char **argv)
{
    tabletype t[MAX];
    t[3].symbol[0] = 'A';

    t[0].value=1;  
    t[0].casenmbr = 7;
    t[0].otherinfo = 682;

    tabletype tabl[MAX];
    tabl[0].value = 1;
    tabl[0].symbol[0] = 'A';
    tabl[1].value = 11;
    tabl[1].symbol[0]= 'a';
    tabl[2].value = 12;
    tabl[2].symbol[0] = 'a';
    tabl[3].value = 13;
    tabl[3].symbol[0] = 'd';
    tabl[4].value = 14;
    tabl[4].symbol[0] = 'e';
    tabl[5].value = 15;
    tabl[5].symbol[0] = 'f';
    tabl[6].value = 16;  
    tabl[6].symbol[0] = 'g';
    tabl[7].value = 17;
    tabl[7].symbol[0] = 'h';
    tabl[8].symbol[0] = 'i';
    tabl[9].symbol[0] = 'x';
    t[1].symbol[0] = 'b';
    t[0].symbol[0]= 'a';
    t[2].symbol[0]= 'c';

    t[4].symbol[0]= 'g';
    printf("char at t.symbol is %s \n", t[3].symbol);

    for( x=0;x<10;x++)
    {
            printf("char at tabl[%d].symbol is %s \n",x, tabl[x].symbol);
    }
    int j;
    for(j = 0; j<5;j++)  
    {
            printf("char at t[%d].symbol is %s \n",j, t[j].symbol);
    }
    return 0;
}

Answer

Gabe picture Gabe · Mar 19, 2010

You have one of two possible problems. If you really just want a single character, you should be printing it with %c, not %s like this:

printf("char at t.symbol is %c \n", t[3].symbol[0]);

If you really want strings you have to define SYMBSIZE to be 1 higher than the maximum length of a symbol and put a NUL (\0) char at the end. You can do it a couple ways:

  1. tabl[6].symbol[0] = 'g'; tabl[6].symbol[1] = '\0';
  2. strcpy(tabl[6].symbol, "g");