Link to home
Start Free TrialLog in
Avatar of jtm082698
jtm082698

asked on

string problems

One last problem with my "getdiskspace" function...
The RootPathName has to hold the app path to give over to the api call, I've tried declaring the variable as a string but that caused problems, I thought the below code would work but it keeps coming up garbage. Code follows ->

char RootPathName[4];

RootPathName[0] = char(_getdrive() + 'A' -1);

RetVal = GetDiskFreeSpace(RootPathName,&SectorsPerCluster,
         &BytesPerSector,&NumberOfFreeClusters,  &TotalNumberOfClusters);
Avatar of jtm082698
jtm082698

ASKER

Edited text of question
ASKER CERTIFIED SOLUTION
Avatar of nietod
nietod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
C strings are arrays of characters that are terminated (end with) a NUL character.  When you declare

char RootPathName[4];

You have an array of 4 random characters.  This is followed by more random bytes that are not really part of the array and may cause an error it they are accessed.   Thus this array does not necessarily represent a string of 3 or 4 characters.  The string begins with the first character and continues through randomly set characters until it happens to come across a NUL character.

When you do

RootPathName[0] = char(_getdrive() + 'A' -1);

you set the first entry in the array to a letter, but the following entries are still random, thus the array does not necessarily hold a NUL terminated string.  

If you want the string to hold only 1 character, you can set the array 2nd entry to NUL by doing

RootPathName[1] = '\0';
Okay, I'm a little confused...can't you set an array or string to a line of text (ex. RootName = "C:\\" or "Hi-Di-Ho Kyle" without the null character)
Yes and no.  

(I guess you want more than that.)  first of all constant literal string, that is, 0 or more characters inside double quotes, like "C:\\", is always represented by the compiler as an array of characters followed by an extra NUL character that you didn't specify.  Thus "ABC" is a 4 character array with 4th character being a NUL.  "ABC\0" is a 5 character array with the 4th and 5th chracters both beng NUL.  So

RootName = "C:\\";

says rootname points to a 4 character array that contains a "C", a  ":", a "\" and then a NUL.  So RootName = "C:\\"; does set rootname to a valid nul terminated string.  Also

char RootName[4] = "C:\\";

does as well and is more like your original code.  But

char RootName[4];

leaves the 4 characters unitialized.  So it could contain a string that goes past the 4 characters allocated.