gpt4 book ai didi

c - 动态字符串数组: allocation in external function

转载 作者:行者123 更新时间:2023-11-30 18:55:47 24 4
gpt4 key购买 nike

我需要你的帮助。

我有一个包含 N 个元素的静态数组。我需要使用函数插入动态分配的字符串。

这是我的代码,有问题:

<< 警告:从不兼容的指针类型传递“插入”的参数 1。 应为“char ***”,但参数类型为“char* (*)[N]”>>

感谢您的帮助!

/* MAIN */
int main()
{
char* array[N];
int i=0;

while (...)
{
i++;
insert(&array, i);
}
...
free(array);
return 0;
}

/* FUNCTION */
void insert(char*** arrayPTR, int i)
{
printf("Enter the string: ");
scanf("%s", string);

(*arrayPTR)[i]=malloc( strlen(string) * sizeof(char) );

strcpy(*arrayPTR[i], string);
}

最佳答案

你就快到了。您的两个主要问题是:

  1. 在将数组传递给函数时,您添加了一个额外的间接层,这是您不需要的,而且实际上会给您带来问题。

  2. 虽然您需要free()各个数组元素,但您不需要也不应该free()数组本身,因为您没有不动态分配它。

下面是它应该看起来更接近的内容:

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

#define N 5
#define MAX_BUFFER 100

void insert(char** arrayPTR, int i);

int main()
{
char* array[N];

/* Populate arrays */

for ( size_t i = 0; i < N; ++i ) {
insert(array, i);
}

/* Print and free them */

for ( size_t i = 0; i < N; ++i ) {
printf("String %zu: %s\n", i + 1, array[i]);
free(array[i]);
}

return 0;
}

void insert(char** arrayPTR, int i)
{
/* Prompt for and get input */

printf("Enter the string: ");
fflush(stdout);
char str[MAX_BUFFER];
fgets(str, MAX_BUFFER, stdin);

/* Remove trailing newline, if present */

const size_t sl = strlen(str);
if ( str[sl - 1] == '\n' ) {
str[sl - 1] = 0;
}

/* Allocate memory and copy */

if ( !(arrayPTR[i] = malloc(strlen(str) + 1)) ) {
perror("couldn't allocate memory");
exit(EXIT_FAILURE);
}
strcpy(arrayPTR[i], str);
}

输出:

paul@thoth:~/src/sandbox$ ./dp
Enter the string: these
Enter the string: are
Enter the string: some
Enter the string: simple
Enter the string: words
String 1: these
String 2: are
String 3: some
String 4: simple
String 5: words
paul@thoth:~/src/sandbox$

关于c - 动态字符串数组: allocation in external function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26451988/

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