You are here:

C/Char Arrays

Advertisement


Question
What am I NOT doing right here? I am trying to experiment with char arrays. I am "watching" both arrays. They initialize correctly, but when I try to pick out the individual elements from the char array inString, I end up with garbage.

I am using Microchip XC8 which is supposed to be ANSI compliant.

// I've assigned 2 char arrays
unsigned char inString[80];
unsigned char tbuf[95];   

// initialize both arrays -- this part works OK
    strcpy(inString,"052841");
    strcpy(tbuf,"");
  
    strcat(tbuf,"TIME");
    strncat(tbuf,inString,2);
    strcat(tbuf,":");
//everything works up to this point

// the next 2 lines give me garbage instead of
// elements 2 and 3 from inString
    strcat(tbuf,inString[2]);
    strcat(tbuf,inString[3];

// this line works correctly
    strcat(tbuf,":");

// more garbage
    strcat(tbuf,inString[4]);
    strcat(tbuf,inString[5]);

// then the "," works correctly
    strcat(tbuf,",");

Thanks,

Keith

Answer
Hi Keith,

There is an error in your program. You are passing a "unsigned char" as a second parameter to strcat instead of the expected "const char *" type.
char *strcat(char *dest, const char *src);
You may create a temporary string with elements two and three from "inString", then used that as a parameter.
Example:

char temp[] = {inString[2],inString[3],'\0'};
strcat(tbuf,temp);

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Tony Nazzal

Expertise

I will answer any c language programming and syntax questions.

Experience

I have almost a decade of c programming experience.

Education/Credentials
I have a bachelor of science degree and several years of industry experience.

©2016 About.com. All rights reserved.