Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Have array[50] want to cut array to array[count] ideas?

Status
Not open for further replies.

Insider1984

Technical User
Feb 15, 2002
132
0
0
US
Basically I have an array that can't be more than 50 chars but maybe from 1-50. When I'm done entering the data I want to use my counter (which tells me how many chars are in the array) to cut the array down to size.


The reason? after this I'm searching the array and having extra junk in a loop they may run 400,000 times will slow it down.

Thanks for the help.
 
You should be aware that a char array has to end with a null terminator '\0'. Otherwise if there desn't happen to have a '\0' just after your string, you will get junk chars when you display the string.
 
as jeffray said you have to end your char arrays with a null. you can also use length = strlen(array) to get the number of characters in the array not including the null. just remeber to minus one if you're starting at 0.
 
Hi,

You should use memory allocation for this. Don't code your array like:

char myarray[50];

This sets aside 50 chars (you can use 49 of them + 1 for the '\0' char if you want it to be a string) and you can't change that...it will always waste space when not needed.

Try looking into using memory allocation with malloc or calloc. This should give you start.

char * ptrToChar, * buf;

...some statements to get the input
ptrToChar = (char*) malloc((strlen(buf) + 1);

Hope that helps.

-Tyler
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top