0

I am trying to implement a function as stated in the title. I think I am very close to solution but a problem.

input: 51% are admitted. output: x:51 (null)

but output should have been:

s:% are admitted.

My try is here:

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

int str2int(int);
int isdigit(int);
long str2double(int);

int driver(char *, char *);

int main(){
    char *s = "51% are admitted.";
    char *sPtr;
    int x = driver(s, sPtr);
    printf("x:%d sPtr:%s", x, sPtr);
    
    return 0;
}

int isdigit(int ch){
    return (ch>=48 && ch<=57)?1:0;
}

int str2int(int ch){
    return ch-48;
}

int driver(char *s, char *sPtr){
    int i=0, number=0;
    while(s[i]!='\0' && isdigit(s[i])){
        number = number*10 + str2int(s[i]);
        i++;
    }
    sPtr=s+i;
    printf("%s\n", sPtr);
    return number;
}

The problem is, in main, sPtr seems as null but in driver function, sPtr is % is admitted which is what it should be. How can I fix the problem so that I can print the solution correctly without using a printf statement in driver function?

EDIT:

The problem is as @Johnny Mopp said, I was trying to pass a copy of that variable. Therefore, I need to pass the address of variable of *sPtr which appears char **sPtr in prototype. And the code should be:

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

int str2int(int);
int isdigit(int);
long str2double(int);

int driver(char *, char **); 

int main(){
    char *s = "51% are admitted.";
    char **sPtr;
    int x = driver(s, &sPtr);
    printf("x:%d sPtr:%s", x, sPtr);
    
    return 0;
}

int isdigit(int ch){
    return (ch>=48 && ch<=57)?1:0;
}

int str2int(int ch){
    return ch-48;
}

int driver(char *s, char **sPtr){
    int i=0, number=0;
    while(s[i]!='\0' && isdigit(s[i])){
        number = number*10 + str2int(s[i]);
        i++;
    }
    *sPtr=s+i;
    return number;
}

Thanks for contributes of @Johnny Mopp and @paulsm4

akoluacik
  • 33
  • 5
  • 2
    To modify what it points to, you need to pass `sPtr` by reference (pointer-to-pointer). Currently you are passing it by value (a copy) so the one in `main` is unaffected. – 001 Sep 03 '21 at 18:44
  • 1
    There are several problems here: 1) a static string literal like `char *s = "..."` might be *READ ONLY*, 2) If the OP wants to use `char *sPtr;` as a separate buffer (recommended!), then he should *ALLOCATE SPACE* for it, 3) the value of `char *sPtr` is *NOT CHANGED* upon returning to the caller (your point); the OP needs `char **sPtr` instead, 4) the OP might want to reconsider his algorithm, so that he doesn't need parameter "sPtr" in the first place. – paulsm4 Sep 03 '21 at 18:48

0 Answers0