user260223
user260223

Reputation: 125

Using strncat with char array element in C

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.

Upvotes: 0

Views: 2466

Answers (3)

Patrick Schlüter
Patrick Schlüter

Reputation: 11841

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.

Upvotes: 0

anon
anon

Reputation:

The expression

name[1] 

is a character - you want a pointer:

strncat(result,name + 1,1);

Upvotes: 2

jkramer
jkramer

Reputation: 15768

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.

Upvotes: 2

Related Questions