views:

149

answers:

3

Hi.. I have get error with the following code and i can't figure it out.

   char name[]="tolgahan"
   char result[100]="";
   strncat(result,name[1],1);

I guess, i need to convert name[1] to string format but i don't now how can i do that.

Please help me. Best regards.

+2  A: 

Try:

strncat(result, & name[1],1);

or

strncat(result, name + 1,1);

Explanation: A string in C is just the address (in memory) of the first character in a sequence of characters. So if you take the pointer (using the & operator or by adding 1 to the initial pointer), you get a string starting at the 2nd character of the initial string.

jkramer
Thank you very much for answer and explanation.
Warning: Note that the above won't work properly if strncat actually has to truncate a string that is too long. stncpy and strncat *stupidly* (IMHO) will not NUL terminate your string in this case. You should always follow a strncpy() or strncat() with (in this example) result[99] = '\0'; to be sure that the resulting string is NUL terminated, or you may end up with a nasty crash. (I say 'stupidly' because a NUL terminated string without a NUL terminator is plain broken, and 'str...' functions are supposed to work with NUL terminated strings, ergo, they should not produce broken strings!)
Jason Williams
@Jason Williams: `strncat` *always* NUL terminates. `strncpy` makes no such guarantee.
jamesdlin
@jamesdlin: ok, fair enough. 'Tis just strncpy that is wildly inconsitent and irritating then :-) (I checked to be sure, but managed to find a rather poor reference page :-)
Jason Williams
+2  A: 

The expression

name[1] 

is a character - you want a pointer:

strncat(result,name + 1,1);
anon
A: 

But using strncat for a 1 character copy is overkill and not really smart.

in your case I would do something more like this

 char name[]="tolgahan";
 char result[100]= "";
 size_t l = 0;
 result[l++] = name[1];

By tracking the length of my first string I can avoid hidden strlen calls (that's what strncat does internally).

 result[l++] = 'H';
 result[l++] = 'e';
 result[l++] = 'l';
 result[l++] = 'l';
 result[l++] = 'o';
 result[l++] = 0;

I still have the real length of my string in l and I avoided a call and the compiler can even rearrange things internally to use fewer memory operations.

tristopia