函数不返回正确的char **指针

时间:2017-11-03 08:31:20

标签: c arrays function

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

//function to change char to upper case
char upper(char ch)
{
    if (ch >= 'a' && ch <='z')
        return ch - ('a'-'A');
    else
        return ch;
}

//Function to find words starting with letter and return array of string words
char **find_words(char *str,char letter, int *size)
{
    char **str_arr=NULL;
    int i=0,j=0;
    int ch;
    int len;


    while (str[j] != NULL)
    {
        ch = str[j];
        while (ch !=' ' && ch !=NULL)
            ch = str[j++];

        str[j-1]=NULL;

        ch = upper(str[i]);
        if ( ch == upper(letter))
        {
            (*size)++;
            str_arr = (char **)realloc(str_arr,(*size)*sizeof(char *));
            len = strlen(&str[i]);
            str_arr[*size] = (char *)malloc((len+1)*sizeof(char));

            strcpy(str_arr[*size],&str[i]);
            printf("\n%s",str_arr[*size]);
        }   
        i=j;
    }

    return str_arr;
}


//Main program to check function find words
void main()
{
    char** str_array=NULL;
    int i,j;
    int size=0;
    char str[] = "Good night go to sleep, Goodman";
    char letter ='g';

    str_array = find_words(str,letter,&size);

    /*
    for (i = 0; i < size; i++)
    {
        printf("\n%s",str_array[i]);
    }
    */

    printf("\n");
}

函数find_words工作并打印动态字符串数组中的单词列表,但在主程序中,返回的指针char **str_arr变为空。

是什么原因?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

我认为您的代码存在增加 size 的问题。后递增可能会解决您的问题。

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



//function to change char to upper case
char upper(char ch)
{
    if (ch >= 'a' && ch <='z')
        return ch - ('a'-'A');
    else
        return ch;
}

//Function to find words starting with letter and return array of string words
char **find_words(char *str,char letter, int *size)
{
    char **str_arr=NULL;
    int i=0,j=0;
    int ch;
    int len;


    while (str[j] != NULL)
    {
        ch = str[j];
        while (ch !=' ' && ch !=NULL)
            ch = str[j++];

        str[j-1]=NULL;

        ch = upper(str[i]);
        if ( ch == upper(letter))
        {

            str_arr = realloc(str_arr,(*size+1)*sizeof(char *));
            len = strlen(&str[i]);
            str_arr[*size] = malloc((len+1)*sizeof(char));

            strcpy(str_arr[*size],&str[i]);
            printf("\n%s",str_arr[*size]);
            //little change here
            (*size)++;
        }   
        i=j;
    }

    return str_arr;
}


//Main program to check function find words
void main()
{
    char** str_array=NULL;
    int i,j;
    int size=0;
    char str[] = "Good night go to sleep, Goodman";
    char letter ='g';

    str_array = find_words(str,letter,&size);


    for (i = 0; i < size; i++)
    {
        printf("\n%s",str_array[i]);
    }

    printf("\n");
}