How can I add the values of an array to a char variable? Without using "strcat" btw.

char table[5],message;
t[0] = "h";
t[1] = "e";
t[2] = "l";
t[3] = "l";
t[4] = "o";

Than end up with "message = "hello""?


Edited by coder_10: n/a

6 Years
Discussion Span
Last Post by hkdani

"message" is declared as a char, so you can only fit one character from t into it.

message = t[0];

Also, you have a char array declared "table" and then you are assigning values using "t". Those should be the same name.

Edited by Mouche: n/a


Ok fine, "char t[5], message;". Regardless how can I add it to "message".

Edited by coder_10: n/a


It looks like you only read the second half of my post. As I said before, "message" is a single char. You cannot add 5 chars to a single char.

If you make "message" a large char array, then you can copy over the characters from "t" to the beginning of "message", one character at a time.


So I make it "message[100]". But how do I do the copying and get a full string at the end?


use a loop to copy from source to destination arrays then null-terminate the destination array. I'm not going to write it for you, you need to figure this out yourself so that you understand it better. Read about loops in your text book or an online tutorial.


Yes I figured as much, except the end part.

char message[1024],t[5];
int a=5;
for (i=0;i<=a;i++) {
message[i] = t[i]
message = "\0"

When or how am I supposed to null terminate the message array (the destination)?

Do I need to do it each time, "message="\0"" or like I have above?


Null terminating means ending the useful data in the char array with a null character (\0). So after your for loop (without line 5), you should do this:

message[a + 1] = '\0';

I'm assuming that "message" is large enough to fit the string you're copying and the null byte.


Your loop is going once too many times, 0 <= 5 is 6, not 5 iterations.

char message[1024],t[5];
int a=5;
int i;
for (i=0;i<a;i++) {
    message[i] = t[i];
message[i] = '\0';

Edited by Ancient Dragon: n/a


OK I have this so far. But when I print the message it only prints the first letter.

char *message[1024],*t[50];
int i,a=5;
t[0] = 'h';t[1] = 'e';t[2] = 'l';t[3] = 'l';t[4] = 'o';

i = 0;
for (i=0;i<=4;i++)
 message[i] = t[i];
message[a + 1] = '\0';


Output is only "h". Its supposed to print "hello".


Good grief. Now you have an array of an array of characters: char *message[1024]. *t[50]; Use char message[1024], t[50] ;

#include <stdio.h>
int main(void)
    char message[]= "hello" ;
    printf("%s\n", message) ;
    return 0 ;

Edited by hkdani: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.