Friday, 15 July 2011

Performing a substring in C -


I'm new to C and I'm currently trying to get the substrings of a string. The final goal I have is a string, which is a set of numbers, i.e. 6218, and I'm taking a substring, so I remove the final number, that is:

  6218 621 62 6   

At this time I'm working hard coding which I want to do, so in the beginning I am doing a substriction of 4, results of the result can still be 6218. However, its 62 when I print it in gdb

Below is the code I'm using.

  char * performSearch (four * phone numbers, integer total lookup number numbers, number lookups * number lists, int maxCharsToLookup) {int i; (I = stellon (phone number); i & lt; maxCharsToLookup; i--) {four search numbers [i + 1]; Strncpy (searchNumber, phoneNumber, 4); Search number [i + 1] = '\ 0'; }}   

The function is called by the following:

  four * displayName = display search (phone number, total lookup number number, number lists, maxcharo Lookup);   

I am moving through code in GDB, so the first thing is that, SearchNumber is printed after the string capacitor, so the loop is not actually used.

I've checked the passed variable and whether Stellen is coming back and its correct

so I expect the search number in the code above, still be 6218, but It is output to 62. Apart from this, only to become aware, the phone number function is passed as four *.

Thank you for any assistance you can provide.

Strlen (phoneNumber); i & lt; maxCharsToLookup; i--)

for maxCharsToLookup to strlen (PhoneNumber) , then it seems that this loop will have to be something when i becomes negative if maxCharsToLookup strlen (phoneNumber)

 for  (count = 0, i = strlen (phoneNumber); count & lt; maxcharstoookup & amp; i> 0 ++ calculation; I) It is difficult to use strncpy ()    

This will only end the NUL destination string if the source string is less string length than the specified length. It's a tough rule to remember Besides this, it will always write the number of bytes you specify to write in the previous parameter. In your code:

  four search numbers [i + 1]; Strncpy (searchNumber, phoneNumber, 4); Search number [i + 1] = '\ 0';   

If i is less than 3, then strncpy () will end your buffer, it will be an undefined behavior, Set NUL to your buffer, which is also undefined. Instead you should do something like this:

  Four Search Numbers [i + 1]; Strncpy (searchNumber, phoneNumber, i); Search number [i] = '\ 0';   

I like using snprintf () . It always terminates the string as a result of NUL.

  #include & lt; Stdio.h & gt; #include & lt; String.h & gt; Int main () {Four phone numbers [] = "6218"; For (int i = strlen (phoneNumber); i>; - i) {four search numbers [i + 1]; Snprintf (searchNumber, sizeof (searchNumber), "% s", phone number); Put (searchNumber); } Return 0; }    

No comments:

Post a Comment