Hi,

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""?


Thanks.

use single quotes, not double quotes. Surround single characters with single quotes.

t[0] = 'h';

OK but how can I add it to "message" than?

Member Avatar for Mouche

"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.

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

Member Avatar for Mouche

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?

Member Avatar for Mouche

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';

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';
 
printf("%s",message);

getch();

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 ;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.