possible workaround for using strncpy

Posted on 2004-08-25
Last Modified: 2012-08-14
How can I copy a certain number of characters in a string onto another string?

If I have the following:
char fname[20], lname[20], nemp[80],*name,*ptr;
name= Archie S. Andrews  
name[strlen(name)-1]='\0'; // to append to terminate string up to this point
By using strrchr I can point to '.' with the address stored in *ptr, and then copy its contents to lname using strcpy.
But how can I use strncpy in such a way that fname will contain only the string "Archie"?

I have tried the code below:
ptr-=2; // this points to S
strcpy(nemp,ptr); // nemp now contains "S. Andrews"
strncpy(fname,name,(strlen(name) - strlen(nemp));

This code prints out "Archie" but followed by some garbage characters and longer than name. One possible solution to this is to append a '\0' at the end of "Archie".  But what if I do not know the actual length of the first name and I only got it from a file?

If you know of another workaround aside from storing the characters one at a time to another character array, please let me know.  I know that storing it by character is possible, but it will have longer code.  Also, I just wish to use pointers to manipulate strings ^^


Question by:jhen04
  • 3
  • 3
  • 2
  • +2

Expert Comment

ID: 11893126
there are some correction  in ur code
  name= "Archie S. Andrews " // should be enclosed in " 
  name[strlen(name)-1]='\0'; // to append to terminate string up to this point
  // you cannot do this with const string pointer. and there is no need for this...

now the solution

memcpy(fname, 0, 20);
ptr = strchr(name, '.');
strncpy(fname, name, (ptr - name - 2 )); // -2 is to move ptr back to <space> after Archie


LVL 22

Expert Comment

ID: 11893258
You could look for the space and replace it with a '\0':

char * p;

p = name;

while( *p != '\0' && *p != ' '  ) p++;

*p = '\0';

LVL 16

Expert Comment

ID: 11893426
I'd use:

char first[20];
char initial[20];
char last[20];

sscanf ( name, "%[^ ] %[^.]. %s", first, initial, last );

The problem with strncpy is that the specified length is the MAXIMUM length it is allowed to build, excluding the terminator. It's more used for limiting the number of characters it copies to the length of the target buffer, avoiding buffer overruns.

sscanf is a much better tool for parsing strings.

Use Case: Protecting a Hybrid Cloud Infrastructure

Microsoft Azure is rapidly becoming the norm in dynamic IT environments. This document describes the challenges that organizations face when protecting data in a hybrid cloud IT environment and presents a use case to demonstrate how Acronis Backup protects all data.

LVL 55

Expert Comment

by:Jaime Olivares
ID: 11893700
Specifically to obtain first name, you can simply copy all the name with strcpy and then trim the string at first blank space if needed:

char *pos;

name="Archie S. Andrews";
strcpy(fname, name);          /* copy entire string */
pos = strchr(fname, ' ');       /* search white space */
if (pos) *pos = '\0';    /* cut at this position if found */

Or, if you prefer:

char *pos;
int len;

name="Archie S. Andrews";
pos = strchr(name, ' ');       /* search white space in original string */
len = pos ? pos-name : strlen(name);   /* calculate new len if a white space exists */
strncpy(fname, name,len);          /* copy desired portion */
fname[len] = '\0';    /* ensure a terminating null is appended */

Hope there are not bugs.

Author Comment

ID: 11893799
what if name="Archie Albert Robert S. Andrews" ?

but actually I've found the solution with a few more tweaks in my program.  Thanks for the info though ^^

Author Comment

ID: 11893887
Thanks for the suggestions dear gurus, however I was able to find the solution myself with a few more tweaks on my code.  Thanks for the infos though ^^

char name[80],*ptr,nemp[80],fname[20],lname[20],mi[2];
// ....... some more codes here
if ((ptr=strstr(buffer,"Name="))!=NULL) // get value for Name
      if (name[strlen(name)-1]=='\n')
          name[strlen(name)-1]='\0';  // remove newline character
      strcpy(nemp,ptr-=1); // ptr-- doesn't work!
      strcpy(lname,ptr); // store last name to lname
      fname[0]='\0';      // initialize fname array to NULL
      printf("%s, %s %s.",lname,fname,mi);
LVL 55

Accepted Solution

Jaime Olivares earned 50 total points
ID: 11893930
strcpy(nemp,ptr-=1); // ptr-- doesn't work!

could be:


Author Comment

ID: 11894106

could be:


..... yup this works.  Thanks!

How can I give you some points for this one? ^^  And how do I close this question?
LVL 55

Expert Comment

by:Jaime Olivares
ID: 11894158
You can request to Community Support to reduce the points instead of delete the question.
LVL 22

Expert Comment

ID: 12906376
I'm a bit peeved that my three line answer didnt get it.

 But whatever.


Featured Post

Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
voltage to force translation ? 8 99
convert char array to number in c 5 86
nested if statement in excel help 4 37
Why  my code (program) build with old compiler? 11 77
This tutorial is posted by Aaron Wojnowski, administrator at  To view more iPhone tutorials, visit This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question