문제

char **rhyme;  // init my double pointer
rhyme=inputrhyme(); // calls below function to input the rhyme

char** inputrhyme(){
    char **rhyme, *temp, *token, BUFF[300], s[2]=" ";
    int length=0;
    rhyme=malloc(length * sizeof(char*));
    printf("please enter a rhyme: \n");
    scanf(" %[^\n]",BUFF);
    token = strtok(BUFF, s);
    while( token != NULL )
    {
        length++;
        temp=realloc(rhyme, length* sizeof(char*));
        if (temp==NULL){
            printf("fatal error!\n");
            exit(EXIT_FAILURE);
        }
        rhyme=temp;
        rhyme[length-1]=token;
        token = strtok(NULL, s);
    }
    length++;
    temp=realloc(rhyme, length* sizeof(char*));
    if (temp==NULL){
        printf("fatal error!\n");
        exit(EXIT_FAILURE);
    }
    rhyme=temp;
    rhyme[length-1]=NULL;

    return rhyme;
}

firstNode=sayRhyme(rhyme, firstNode); // goes through the rhyme saying each word

NodePtr sayRhyme(char **rhyme,  NodePtr starting_player){
    int index;
    NodePtr temp=starting_player;
    printf(" %s\n", rhyme[6]);  // works fine for all valid values
    for (index=0; index<9; index++){
        printf("---------%d %s\n",index, rhyme[index]);  // problem area
    }

above is almost all the code that involves this rhyme. when i pass my double pointer to my function, i only need to read it so i didn't pass a pointer to it. i can read any value in the rhyme, but when i try to put it through a loop the data becomes corrupted some how. this is the output i get:

please enter a rhyme:
help im stuck in a computer for real now  *user input*
help
im
stuck
in
a
computer
for
real
now
first word was help
 for
---------0 help
---------1 im
---------2 stuc$
---------3
---------4
▓
---------5
---------6 for
---------7 ▄²(
---------8 ≥7vÅ≥7vδ╛ΣW
player 0 is eliminated

I'm not sure what I'm doing wrong here. i tried to pass the double pointer as a triple and deference it with the same results.

도움이 되었습니까?

해결책

You are saving your string into a local array BUFF which will be stored on the stack.

When you call strtok to break it into tokens it will return pointers back into the BUFF array.

When you return from your function, the stack space is freed and may be reused by other parts of the program.

You need to store the string in a better place, e.g. in a global array or in a block of malloced memory.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top