c - 动态数组和扫描字符串的 ANSI C 问题

标签 c arrays pointers

我在 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;
}

最佳答案

https://godbolt.org/z/zj_QpY

#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/

相关文章:

c++ - 以十进制打印变量地址

string - Swift REPL 意外行为

将 GhostPDL 编译为 DLL

c - 在C中打印字符串中的所有字符

arrays - 将 [Int?] 转换为 [Int]

C编译时断言常量数组

python - 将两个 numpy 数组转换为成对数组的数组

c - 删除C中括号内的字符

c - c中的字符串文字

c - 各个 CPU 之间的 float 是否一致?