我在 ANSI C 中遇到了这个小程序的问题。我想编写一个具有三个功能的程序 - 创建动态数组 (stworz_tablice)、加载数据 - 字符串 (pobierz_tablice) 并打印它 (wypisz_tablice)。
所以程序是这样工作的:我们为数组提供一个数字,放入一个字符串,函数应该将其写入控制台。例如输入:4火
如何更正代码使其正常工作?
我认为问题在于 mytab = stworz_tablice(n);
,但我还不知道如何修复它。
当我执行程序时,它不需要字符串。输出就像一些随机数字而不是字母。
输入:
4
Anna
我想要的输出:
Anna
我每次得到的输出:
-24244 -24242 0 0 // Some random numbers, every time different ones
#include <stdlib.h>
char *stworz_tablice(int n)
{
char *mytab = (char*)malloc((n+1) * sizeof(char));
if (mytab == NULL)
{
perror("Error in malloc");
exit (1);
}
return mytab;
}
void pobierz_tablice(char *mytab, int n)
{
scanf ("%s", mytab);
}
void wypisz_tablice(char mytab[], int n)
{
for(int i=0; i<n; i++)
printf("%c",mytab[i]);
}
int main(void)
{
int *mytab;
int n;
scanf("%d", &n);
if (n<=0)
{
printf("BŁĄD");
return 0;
}
mytab = stworz_tablice(n);
pobierz_tablice(mytab, n);
wypisz_tablice(mytab, n);
putchar('\n');
free(mytab);
return EXIT_SUCCESS;
}
最佳答案
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
char *stworz_tablice(int n)
{
char *mytab = malloc(n+1);
if (mytab == NULL)
{
perror("Error in malloc");
exit (1);
}
return mytab;
}
int pobierz_tablice(char *mytab, int n)
{
return scanf ("%s", mytab);
}
void wypisz_tablice(char mytab[], int n)
{
for(int i=0; i<n; i++)
printf("%c",mytab[i]);
}
int main(void)
{
char *mytab;
int n;
scanf("%d", &n);
if (n<=0)
{
printf("BŁĄD");
return 0;
}
mytab = stworz_tablice(n);
if(pobierz_tablice(mytab, n) != 1)
{
perror("Scanf error\n");
exit (1);
}
wypisz_tablice(mytab, n);
putchar('\n');
free(mytab);
return EXIT_SUCCESS;
}
关于c - 动态数组和扫描字符串的 ANSI C 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59737091/