Print character array (C) First letter only

I need to fill manually a character array. I have declared the following:

char* coor = malloc(sizeof(char) * 5);

      

Then I manually assigned each variable to its position:

coor[0] = O_colum;
coor[2] = ((char)(O_row+48));

coor[3] = '-';
coor[4] = D_colum;

coor[5] = ((char)(D_row+48));

      

( D_Row

and O_row

are integers, I need that number in character form, not the equivalent value in ASCII, so I do +48

)

The problem occurs when I try to print it. If I use printf(" %s", coor)

it only prints the first characters and I don't know why. I'm using %s

, so it should print all characters in the string. When I do this:

char *p = "hello";
printf("%s",p);

      

He is typing hello

.

+3


source to share


1 answer


There are two errors in the code:

  • you are missing position 1 of the array. This is probably the reason why it only prints the first item.
  • you need to add a trailing line character \0

    at the end of the line.


This should fix:

char* coor = malloc(sizeof(char) * 6);

coor[0] = O_colum;
coor[1] = ((char)(O_row+48));

coor[2] = '-';
coor[3] = D_colum;

coor[4] = ((char)(D_row+48));
copr[5] = '\0';

      

+2


source







All Articles