gpt4 book ai didi

c - 函数未返回正确的 char** 指针

转载 作者:行者123 更新时间:2023-11-30 14:53:40 24 4
gpt4 key购买 nike

#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变为空。

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

最佳答案

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

#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");
}

关于c - 函数未返回正确的 char** 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47091391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com