简体   繁体   English

使用malloc()和realloc()将字符串存储在数组中

[英]Using malloc() and realloc() to store strings in an Array

getWordsArray() gets a pointer to a char array - the input. getWordsArray()获取一个指向char数组的指针-输入。

Im trying to split that input and store each word in a char array. 我试图拆分输入并将每个单词存储在char数组中。 And eventually return that char array. 并最终返回该char数组。

   char *getWordsArray(char *input)
    {
        char *token;
        char *search = " ,";
        char *splited, *temp;
        int counter=0;
        splited = malloc(sizeof(char)*15);
        token = strtok (input,search);
        while (token != NULL ) {
            printf("%s\n",token);
            token = strtok (NULL,search);
          //  splited[counter] = *token;  //aliasing ?
            strcpy(&splited[counter] , token);
            temp= realloc(splited,(counter+1)*sizeof(token));
            if (temp !=NULL) {
                splited = temp;
            } else{
                free(splited);
                printf("Error allocating memory!\n");
                return 0 ;
            }
            counter++;
        }
        printf("list is: %s\n",splited);
        return splited;
    }

It seems like it works since it prints correctly. 由于可以正确打印,因此似乎可以正常工作。 But i get: 但是我得到:

EXC_BAD_ACCESS

on

strcpy(&splited[counter] , token);

Anyone can point me out whats wrong ? 任何人都可以指出我有什么问题吗?

Your function return type is all wrong; 您的函数返回类型都是错误的; it needs to be char ** , not just char * . 它必须是char ** ,而不仅仅是char * The allocation strategy in the function is wrong, too, therefore. 因此,功能中的分配策略也是错误的。 You need to allocate an array of char * as well as an array of char for each component word that is stored in the array of char * . 您需要为存储在char *数组中的每个组成词分配一个char *数组以及一个char数组。

When you copy the string, eg on strcpy(&splited[counter] , token); 当您复制字符串时,例如在strcpy(&splited[counter] , token); , it is very likely, that it's too long for the destination. ,很可能目的地太长了。 That is because you do not allocate an array of strings but an array of char . 那是因为您没有分配一个字符串数组,而是一个char数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM