gpt4 book ai didi

c - 使用指针和动态存储在启动时传递未知大小的字符串的程序

转载 作者:太空宇宙 更新时间:2023-11-04 08:38:49 25 4
gpt4 key购买 nike

这是我的任务:

Write a program and the following functions using dynamic storage to manipulate the character strings.

a. A function to input an unknown number of character strings of unknown length (max 80) and store each string in dynamic storage.

b. A function to output each character string and its corresponding length in terms of the number of characters.

The program should begin by reading the number of character strings to be processed and allocating dynamic storage for the pointers.

我的代码如下。此版本编译良好但在尝试获取输出时中断。

感谢任何帮助。

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


int funcinput (char **, int *,char *);
void funcoutput (char **, int *);

int main()
{
char c;
int *n;
char *ptr;
char **userinput=calloc(*n,80);

funcinput (userinput,&*n,&*ptr);
funcoutput (userinput,&*n);
}


int funcinput(char **userinput, int *n, char *ptr)
{
char c;
int counter =0;
int max=0;

printf("How many items are in your list\n");
scanf("%d",&*n);

max = *n;

ptr = (char*)calloc(*n,80);

printf("Enter your list, each item can be a max of 80 characters long:\n");
for (counter=0;counter<*n;counter++)
{
scanf("%80s",&userinput[c]);
}
return;
}

void funcoutput (char **userinput,int *n)
{
char c;
int counter1=0;
int max1=0;

max1 = *n;

printf ("You entered %d strings of charectors\n",*n);
printf ("The following is the list you entered \n");
for(counter1=0;counter1<max1;counter1++)
{
printf("\n%-80s \n",*userinput[c]);
}
return;
}

最佳答案

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

char **funcinput (int *size /* out */);
void funcoutput (char **out_array, int size);

int main(){
//char c;//unused
int n;
//char *ptr;//unused
char **userinput = funcinput(&n);

funcoutput(userinput, n);
//deallocate
int i;
for(i=0;i<n;++i){
free(userinput[i]);
}
free(userinput);
return 0;
}

char **funcinput(int *n){// n : output size
int counter =0;
int max=0;

printf("How many items are in your list\n");
scanf("%d", n);

max = *n;

char **userinput = calloc(max, sizeof(char*));

printf("Enter your list, each item can be a max of 80 characters long:\n");
for (counter=0;counter < max;counter++){
userinput[counter] = calloc(80, sizeof(char));
if(1!=scanf("%79s", userinput[counter])){//spaces not includes
free(userinput[counter]);
break;
}
}
*n = counter;
return userinput;
}

void funcoutput (char **userinput,int n){
int counter=0;
int max=n;

printf ("You entered %d strings\n", n);
printf ("The following is the list you entered \n");
for(counter=0;counter<max;counter++){
printf("%s\n", userinput[counter]);//%-80s : Probably not necessary
}
}

关于c - 使用指针和动态存储在启动时传递未知大小的字符串的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24814580/

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