开发者

Am I passing a copy of my char array, or a pointer?

I've been studying C, and I decided to practice using my knowledge by creating some functions to manipulate strings. I wrote a string reverser function, and a main function that asks for user input, sends it through stringreverse(), and prints the results.

Basically I just want to understand how my function works. When I call it with 'tempstr' as the first param, is that to be understood as the address of the first element in the array? Basically like saying &tempstr[0], right?

I guess answering this question would tell me: Would there be any difference if I assigned a char* pointer to my tempstr array and then sent that to stringreverse() as the first param, versus how I'm doing it now? I want to know whether I'm sending a duplicate of the array tempstr, or a memory address.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char* stringreverse(char* tempstr, char* returnptr);

    printf("\nEnter a string:\n\t");

    char tempstr[10开发者_如何转开发24];

    gets(tempstr);
    char *revstr = stringreverse(tempstr, revstr); //Assigns revstr the address of the first character of the reversed string.

    printf("\nReversed string:\n"
           "\t%s\n", revstr);

    main();
    return 0;
}

char* stringreverse(char* tempstr, char* returnptr)
{
    char revstr[1024] = {0};

    int i, j = 0;

    for (i = strlen(tempstr) - 1; i >= 0; i--, j++)
    {
        revstr[j] = tempstr[i]; //string reverse algorithm
    }

    returnptr = &revstr[0];
    return returnptr;
}

Thanks for your time. Any other critiques would be helpful . . only a few weeks into programming :P

EDIT: Thanks to all the answers, I figured it out. Here's my solution for anyone wondering:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void stringreverse(char* s);

int main(void)
{
    printf("\nEnter a string:\n\t");

    char userinput[1024] = {0}; //Need to learn how to use malloc() xD

    gets(userinput);
    stringreverse(userinput);

    printf("\nReversed string:\n"
           "\t%s\n", userinput);

    main();
    return 0;
}

void stringreverse(char* s)
{
    int i, j = 0;
    char scopy[1024]; //Update to dynamic buffer
    strcpy(scopy, s);

    for (i = strlen(s) - 1; i >= 0; i--, j++)
    {
        *(s + j) = scopy[i];
    }
}


First, a detail:

int main()
{
    char* stringreverse(char* tempstr, char* returnptr);

That prototype should go outside main(), like this:

char* stringreverse(char* tempstr, char* returnptr);

int main()
{

As to your main question: the variable tempstr is a char*, i.e. the address of a character. If you use C's index notation, like tempstr[i], that's essentially the same as *(tempstr + i). The same is true of revstr, except that in that case you're returning the address of a block of memory that's about to be clobbered when the array it points to goes out of scope. You've got the right idea in passing in the address of some memory into which to write the reversed string, but you're not actually copying the data into the memory pointed to by that block. Also, the line:

returnptr = &revstr[0];

Doesn't do what you think. You can't assign a new pointer to returnptr; if you really want to modify returnptr, you'll need to pass in its address, so the parameter would be specified char** returnptr. But don't do that: instead, create a block in your main() that will receive the reversed string, and pass its address in the returnptr parameter. Then, use that block rather than the temporary one you're using now in stringreverse().


Basically I just want to understand how my function works.

One problem you have is that you are using revstr without initializing it or allocating memory for it. This is undefined behavior since you are writing into memory doesn't belong to you. It may appear to work, but in fact what you have is a bug and can produce unexpected results at any time.

When I call it with 'tempstr' as the first param, is that to be understood as the address of the first element in the array? Basically like saying &tempstr[0], right?

Yes. When arrays are passed as arguments to a function, they are treated as regular pointers, pointing to the first element in the array. There is no difference if you assigned &temp[0] to a char* before passing it to stringreverser, because that's what the compiler is doing for you anyway.

The only time you will see a difference between arrays and pointers being passed to functions is in C++ when you start learning about templates and template specialization. But this question is C, so I just thought I'd throw that out there.


When I call it with 'tempstr' as the first param, is that to be understood as the address of the first element in the array? Basically like saying &tempstr[0], right?

char tempstr[1024];

tempstr is an array of characters. When passed tempstr to a function, it decays to a pointer pointing to first element of tempstr. So, its basically same as sending &tempstr[0].

Would there be any difference if I assigned a char* pointer to my tempstr array and then sent that to stringreverse() as the first param, versus how I'm doing it now?

No difference. You might do -

char* pointer = tempstr ; // And can pass pointer

char *revstr = stringreverse(tempstr, revstr); 

First right side expression's is evaluavated and the return value is assigned to revstr. But what is revstr that is being passed. Program should allocate memory for it.

char revstr[1024] ;
char *retValue = stringreverse(tempstr, revstr) ;
     // ^^^^^^ changed to be different.

Now, when passing tempstr and revstr, they decayed to pointers pointing to their respective first indexes. In that case why this would go wrong -

revstr = stringreverse(tempstr, revstr) ;

Just because arrays are not pointers. char* is different from char[]. Hope it helps !


In response to your question about whether the thing passed to the function is an array or a pointer, the relevant part of the C99 standard (6.3.2.1/3) states:

Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.

So yes, other than the introduction of another explicit variable, the following two lines are equivalent:

char x[] = "abc";                     fn (x);
char x[] = "abc"; char *px = &(x[0]); fn (px);

As to a critique, I'd like to raise the following.


While legal, I find it incongruous to have function prototypes (such as stringreverse) anywhere other than at file level. In fact, I tend to order my functions so that they're not usually necessary, making one less place where you have to change it, should the arguments or return type need to be changed. That would entail, in this case, placing stringreverse before main.


Don't ever use gets in a real program.. It's unprotectable against buffer overflows. At a minimum, use fgets which can be protected, or use a decent input function such as the one found here.


You cannot create a local variable within stringreverse and pass back the address of it. That's undefined behaviour. Once that function returns, that variable is gone and you're most likely pointing to whatever happens to replace it on the stack the next time you call a function.


There's no need to pass in the revstr variable either. If it were a pointer with backing memory (i.e., had space allocated for it), that would be fine but then there would be no need to return it. In that case you would allocate both in the caller:

char tempstr[1024];
char revstr[1024];
stringreverse (tempstr, revstr); // Note no return value needed
                                 //  since you're manipulating revstr directly.

You should also try to avoid magic numbers like 1024. Better to have lines like:

#define BUFFSZ 1024
char tempstr[BUFFSZ];

so that you only need to change it in one place if you ever need a new value (that becomes particularly important if you have lots of 1024 numbers with different meanings - global search and replace will be your enemy in that case rather than your friend).


In order to make you function more adaptable, you may want to consider allowing it to handle any length. You can do that by passing both buffers in, or by using malloc to dynamically allocate a buffer for you, something like:

char *reversestring (char *src) {
    char *dst = malloc (strlen (src) + 1);
    if (dst != NULL) {
        // copy characters in reverse order.
    }
    return dst;
}

This puts the responsibility for freeing that memory on the caller but that's a well-worn way of doing things.


You should probably use one of the two canonical forms for main:

int main (int argc, char *argv[]);
int main (void);

It's also a particularly bad idea to call main from anywhere. While that may look like a nifty way to get an infinite loop, it almost certainly will end up chewing up your stack space :-)


All in all, this is probably the function I'd initially write. It allows the user to populate their own buffer if they want, or to specify they don't have one, in which case one will be created for them:

char *revstr (char *src, char *dst) {
    // Cache size in case compiler not smart enough to do so.
    // Then create destination buffer if none provided.

    size_t sz = strlen (src);
    if (dst == NULL) dst = malloc (sz + 1);

    // Assuming buffer available, copy string.

    if (dst != NULL) {
        // Run dst end to start, null terminator first.

        dst += sz; *dst = '\0';

        // Copy character by character until null terminator in src.
        // We end up with dst set to original correct value.

        while (*src != '\0')
            *--dst = *src++;
    }

    // Return reversed string (possibly NULL if malloc failed).

    return dst;
}


In your stringreverse() function, you are returning the address of a local variable (revstr). This is undefined behaviour and is very bad. Your program may appear to work right now, but it will suddenly fail sometime in the future for reasons that are not obvious.

You have two general choices:

  1. Have stringreverse() allocate memory for the returned string, and leave it up to the caller to free it.
  2. Have the caller preallocate space for the returned string, and tell stringreverse() where it is and how big it is.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜