gpt4 book ai didi

c - 返回指向字符串数组的指针 C

转载 作者:行者123 更新时间:2023-12-04 02:58:22 24 4
gpt4 key购买 nike

我正在尝试返回一个从文件中获取的字符串数组。该文件看起来像这样(第一行是单词数,每一行都是单词)。当功能结束时,我在主要部分得到一些奇怪的输出。我想返回指向字符串数组的指针。请注意,使用打印的部分代码用于检查我的程序。

这是分配内存的函数:

char *generisiProstor(int n) {
return (char*)malloc(n*sizeof(char[20]));
}

这是从 rijeci.txt 中获取单词的函数,应该返回指向包含单词的字符串数组的指针:

char* ucitajRijeci(int n) {

char i;
char *rijeci;

static const char filename[] = "rijeci.txt";
FILE *file;
file = fopen(filename, "r");
if (file != NULL)
{
char line[20];
int n;
fscanf(file, "%d", &n);
rijeci = generisiProstor(n);
if (rijeci == NULL) {
return NULL;
}
int i = -1;

fgets(line, 20, file); //skipping first line witch is integer and not needed
while (fgets(line, 20, file) != NULL)
{
printf("%s\n", line); //normal output
i++;
strcpy(rijeci + i, line);
printf("%s\n", rijeci + i); //normal expected output
}
for (i = 0; i < n; i++) {
printf("%s\n", rijeci + i); //wrong output
}
}
return rijeci;
}

主要

int main()
{
static const char filename[] = "rijeci.txt";
FILE *file;
file = fopen(filename, "r");
char *rijeci;
int i;
if (file != NULL)
{
char line[20];
int n;
fscanf(file, "%d", &n);
rijeci = ucitajRijeci(n);
printf("Here is the array: ");
for (i = 0; i < n; i++) {
printf("%s ", rijeci+i); //wrong output
}
}
return 0;
}

最佳答案

这里必须使用二维数组(char ** 而不是 char *)。由于您要返回二维数组,因此您必须将 rijeci 声明为 char **rijeci;

  1. 两个函数的返回类型也应该是char **
  2. rijeci + i 更改为 rijeci[i]
  3. 正确的代码缩进。

试试这个修改后的代码。这将起作用:-

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

/* generisiProstor */

char **generisiProstor(int n)
{
char **c; // making 2-d array
c = (char **)malloc(n * sizeof(char *));
for (int i = 0; i < n; i++)
{
c[i] = (char *)malloc(20 * sizeof(char));
}
return c;
}

/* ucitajRijeci */

char **ucitajRijeci(int n)
{

char **rijeci; // change to char **

static const char filename[] = "rijeci.txt";
FILE *file;
file = fopen(filename, "r");
if (file != NULL)
{
char line[20];
int n;
fscanf(file, "%d", &n);
rijeci = generisiProstor(n);
if (rijeci == NULL)
{
return NULL;
}
int i = -1;

fgets(line, 20, file); //skipping first line witch is integer and not needed
while (fgets(line, 20, file) != NULL)
{
printf("%s\n", line); //normal output
i++;
strcpy(rijeci[i], line);
printf("%s\n", rijeci[i]); //changed to rijeci[i]
}
for (i = 0; i < n; i++)
{
printf("%s\n", rijeci[i]); //changed to rijeci[i]
}
}
return rijeci;
}

/* main() */

int main()

{

static const char filename[] = "rijeci.txt";
FILE *file;
file = fopen(filename, "r");
char **rijeci; // change to char **
int i;
if (file != NULL)
{
char line[20];
int n;
fscanf(file, "%d", &n);
rijeci = ucitajRijeci(n);
printf("Here is the array: ");
for (i = 0; i < n; i++)
{
printf("%s ", rijeci[i]); //changed to rijeci[i]
}
}
return 0;
}

关于c - 返回指向字符串数组的指针 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51661127/

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