Frage

I'm trying to simulate passing by reference and apparently I'm doing something wrong:

long int toNumber(char * input) {
   char* pointer;
   long int number;
   number = strtol(input, &pointer, 10);
   if (number == 0L) {
       return -1337;
   } else {
       input = pointer;
       return number;
   }
}

I'd like for this function to return the value of the input and trim the converted beginning of it, yet when I try calling it, even though the integer conversion is flawless, the string remains the same. Thanks for any kind of help.

Edit:

    char* input = "123 456"; 
    long int number = toNumber(input);

Edit 2: Changed back, sorry. I'd like for it to work something like this: input = 123 456 -> number = 123, input = 456 -> number = 456, input = NULL

War es hilfreich?

Lösung

It is not clear about the 1337 thing... however, this code should produce what the question code is attempting with simplified logic.

long int toNumber(char **input) 
   { 
   char *pointer;
   long int number;

   number = strtol(input, &pointer, 10);
   if(number)
      *input = pointer;
   else
      number = (1337);

   return number;
   }

Something like the following call the above function:

   {
   char *test="123 456";
   long int n;

   ...

   n = toNumber(&test);

   printf("n[%ld] remainder[%s]\n", n, test);       
   ...

   }

Which should print:

n[123] remainder[ 456]

Andere Tipps

input is a pointer, which is passed by value to your toNumber function. Assigning a value to input merely changes the parameter object, which is local to the function. It has no effect on the caller.

To modify the string, you'd have to modify *input, or input[some_index], or pass input to some other function that will modify the data that it points to.

Note that updating a string in place is not necessarily a good idea. You can modify the characters that make up the string, but you can't increase the size of the array containing the string. And if the caller passes a string literal, then attempting to modify it has undefined behavior (and will likely crash your program).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top