Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

Spliting string and storing in array or pointer in C

I'm working in a little project, i have some names stored in a struct (example: Name1, Name2) and I need to split each one and store it in a array so I can call then each name separately (printf("%s", vet[1]) should print only "Name2").

This is my code:

int main(){

    char temp[100];
    LIGA *vetLiga;
    int reference;
    int quantiy;


    separarEquipas(vetLiga, temp, reference, quantity);
}

int separarEquipas(LIGA *p, char vet[100], int vPesquisa, int n){
    
    int i, nr, a;
    char *ptr;
    char *str;
    
    for(i=0;i<n;i++){
        
        if (p->id == vPesquisa){
                nr = p->nrEquipas;
                strcpy(str, p[i].eqLiga);
                ptr = strtok(str, " ,"); 
                
                while(ptr != NULL) 
                {
                    vet[a++] = ptr; //here I'm trying to store each word in a position of the array
                    ptr = strtok(NULL, " ,");
                }
        }
        p++;
    }
    
    return nr;
}

The issue is inside the while where I try to store each token in the array but it keeps crashing the terminal. I tried in different ways like using strcpy and memcpy as other posts suggest but nothing :(.

Some errors that i got while trying to find a solution:

[Warning] assignment makes integer from pointer without a cast; [Warning] passing argument 1 of 'strcpy' makes pointer from integer without a cast.

Hope you can help me, Thank you!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You didn't post the full code, so from what I can see vetLiga that in separarEquipas becomes p is uninitialised.

Another issue is that you try to use str in strcpy without allocating memory for it. You need to do that

char *str = malloc( max_number_of_characters_in_str );

Then here:

vet[a++] = ptr; //here I'm trying to store each word in a position of the array

You are doing exactly what you said in the comment. However you can't store a word into the space for a single character. vet needs to be a 2D array or if you want even an array of pointers to char.

If you want further help include the whole program.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...