Connecting Tech Pros Worldwide Forums | Help | Site Map

fun with casting

Newbie
 
Join Date: Jan 2007
Posts: 1
#1: Jan 5 '07
Hello All,

I'm trying to do a simple c program that will squish together several char arrays to create one large char array.

I'd like to be able to take "abc" "defg" "hijk" and create "abcdefghijk".

Here's what I have so far:

void squishChars(char *final, char *array ){

int i;
for (i=0; array[i]; i++){
strcat(final, array[i]);
}

}

final is the resulting squished char array ( in my example "abcdefghijk" )
array is similar to the following
const char *letters[] = {
"abc",
"defg",
"hijk",
NULL
};

When I attempt to compile, these are the errors I'm getting:
warning: passing arg 2 of `strcat' makes pointer from integer without a cast
warning: passing arg 2 of `squishChars' from incompatible pointer type

Running causes major trouble... a Status Access Violation.

I realize I need to cast array[i] as a char array, but I'm not sure how to do it... any ideas?

Thanks in advance!

- JB

Expert
 
Join Date: Nov 2006
Location: UK
Posts: 1,320
#2: Jan 5 '07

re: fun with casting


the destination for strcat() should be a char[] (not const) with sufficent room for the concatenated characters. e.g.
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. void squishChars(char *final, char *array[] ){
  5. int i;
  6. for (i=0; array[i]!=NULL; i++)
  7.     strcat(final, array[i]);
  8. }
  9.  
  10. int main()
  11. {
  12.      const char *letters[] = {"abc","defg","hijk",NULL};
  13.      char output[50]="xyz";
  14.      squishChars(output, letters);
  15.      printf("%s\n", output);
  16.      system("pause");
  17. }
  18.  
when run gives
xyzabcdefghijk
Reply