2

I am trying to split up an array (string1) of n characters into two character pointers representing i characters (char* first) and n-i characters (char* second) respectively. For the second array, I used

char* second = string1+n; 

What I am wondering is how to use only the first i characters in first. I do not want to allocate more memory for the two arrays, I want to manipulate string1 so that I just point to parts of what is already there.

EDIT:

I cannot edit string1. Can I just cast first somehow to make the length shorter without adding a null character?

2
  • In response to your edit, no, you need to copy it. You can use strndup(), which takes a length, to only copy a certain portion of it and have memory allocated automatically. Commented Feb 1, 2012 at 3:35
  • possible duplicate of How to retrieve n characters from char array Commented Feb 1, 2012 at 10:54

2 Answers 2

2

Unless you allocate more memory you can't use the "first" as you would any other C string (e.g. passing it to string functions, printf, etc) because it isn't null terminated at the boundary with "second".

You can certainly still get around that in many cases because you know the length, but there's nothing magical you can do here; the null terminator needs a byte.

Sign up to request clarification or add additional context in comments.

2 Comments

Can I cast string1 somehow to make the pointer think it's only i length?
No. Don't know what else to tell you, that's not how it works.
1

Strings in C have to be NULL-terminated, i.e. have a \0 character at the end of them. If you had, for example, two words split by a space, like so:

char *str1 = "fat chance";

You could "split" them by replacing the space with \0:

str1[3] = '\0';

And then set str2 to point to after the \0:

char *str2 = str1 + 4;

However, if you need something to be split where there isn't a convenient place to put in a terminator, then you need to copy the second part of the string elsewhere. The easiest way to do this (if you don't mind having to free() it later), is to use strdup(), and putting a NULL terminator in str1 afterward:

char *str2 = strdup(str1 + 4);
str1[4] = '\0';

2 Comments

I am assuming that strdup allocates memory since I need to use free later, correct?
@mrswmmr, yessir. It saves you from having to use malloc() yourself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.