Thread: I dont Know

  1. #1
    Registered User
    Join Date
    Feb 2009
    Location
    Indiana
    Posts
    99

    I dont Know

    I dont know where to start.

    Write two versions of function strlen in Fig. 8.36. The first version should use array subscripting, and the second version should use pointers and pointer arithmetic.


    8.36 says this:

    size_t strlen(const char *s);
    Determines the length of string s. The number of characters preceding the terminating null character is returned.

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    No. 1 refers to this:
    Code:
    char string[]="this and that";
    int i=0;
    while (string[i]!='\0') {
           ...etc.
    the "array subscript" is the [bracketed element number].

    No. 2 is this kind of stuff
    Code:
    char string[]="this and that";
    char *ptr=string;
    int dif;
    while (ptr!='\0') { ptr++; }
    dif=ptr-string;
    See? Pointer arithmetic. Memory addresses are in bytes, which are equal to one char, so for example the address "&string[1]" will be one integer value higher than "*string" itself.

    I am pretty sure this is guaranteed by the compiler. Positive actually.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Registered User
    Join Date
    Feb 2009
    Location
    Indiana
    Posts
    99
    Ok I think I get the 2nd one. The first one tho is where Im confused at. What am I using strlen for? Like what u have, what does that have to do with strlen?

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    I would lie and say that it has nothing to do with strlen, but if I tell the truth and say it is 3/4 of strlen, will you believe "i++" is at least another 1/8th of that algorithm?
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed