referring to a[-1],a[len]

This is a discussion on referring to a[-1],a[len] within the C Programming forums, part of the General Programming Boards category; take this function Code: /* this checks if t is at the end of s*/ int mystrend(char* s,char* t){ int ...

  1. #1
    Registered User
    Join Date
    Oct 2005
    Hyderabad, India

    referring to a[-1],a[len]

    take this function
    /* this checks if t is at the end of s*/
    int mystrend(char* s,char* t){
        int l1 = strlen(s);
        int l2 = strlen(t);
        if(l2 > l1) return 0;
        s = s + l1 - 1;
        t = t + l2 - 1;
    	if(*s-- != *t--)
    	    return 0;
        return 1;
    in case of passing empty strings i make s = s -1; i won't be using the values or writing to these locations.

    i heard that it is fine to refer to these (one less and one more) , am i correct ? Please explain.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Why don't you simply rewrite your function to check for null pointers and empty strings? You can only refer to the place after valid array elements to compare its address. I believe pointing before memory allocated, even for address comparison, even to check against null, creates in effect an invalid pointer, which means anything you do to it is undefined behavior. (IE: Bad.) You are only allowed to check the address of an array / block of memory for "one past". Nothing more. IE:
    int array[ 5 ];
    int *ptr = array;
    if( ptr < array + 5 ) /* Ok. */
    if( ptr < array + 6 ) /* Not ok. */
    Hope is the first step on the road to disappointment.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Rather than the while loop, just have

    return strcmp( s+l1-l2, t ) == 0;
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. GNU Build System and referring to Libraries
    By orwb in forum Linux Programming
    Replies: 7
    Last Post: 12-06-2007, 03:41 AM
  2. Referring to an unknown element
    By Daniel Primed in forum C++ Programming
    Replies: 2
    Last Post: 01-07-2006, 10:39 AM
  3. Two Classes Referring to each other
    By jwong78 in forum C++ Programming
    Replies: 19
    Last Post: 12-12-2005, 04:56 PM
  4. Referring to a C String
    By cpluspluser in forum C++ Programming
    Replies: 1
    Last Post: 04-09-2003, 07:13 PM
  5. Just a tiny little problem...
    By Nutshell in forum C Programming
    Replies: 26
    Last Post: 02-08-2003, 04:54 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21