检查结构数组中非空字符串的数量;将NULL值赋给结构数组中的char数组

时间:2014-01-21 00:18:33

标签: c arrays function struct char

函数应该在结构数组中返回许多非空字符串。输入值后,程序停止工作。
第二个问题:如何为 Lancuch 结构数组中的一个 L 元素分配空值?

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

typedef struct{
    char L[100];
} Lancuch;

int funkcja5 (Lancuch[], int);

int main()
{
    Lancuch st[3];
    scanf("%s",&st[0].L);
    scanf("%s",&st[1].L);
    scanf("%s",&st[2].L);
    printf("%s\n",funkcja5(st,3));
    return 0;
}

int funkcja5 (Lancuch s[], int n)
{
    int i = 0, suma = 0;
    for(;i<n;i++)
    {
        if(strlen(s[i].L) > 0)
        {
            suma++;
        }
    }
    return suma;
}

1 个答案:

答案 0 :(得分:0)

这可能是你看到的崩溃。

printf("%s\n",funkcja5(st,3));

funkcja返回一个int,但您使用了格式说明符"%s"。它应该是"%d"

此外,还有以下表达式:

&st[0].L

导致char (*)[100],即指向char[100]数组的指针,而不是指向scanf期望的char的指针。数组不是指针,并且获取数组的地址会产生指向数组的指针。这似乎有时会起作用,但是您正在调用未定义的行为。

你想要的是让数组降级为指向第一个元素的指针,所以......

scanf("%s",st[0].L);
/* and so on... */

当然,你仍然可以在这里使用缓冲区溢出。 scanf无法安全使用;改为使用fgets

if(fgets(st[0].L, sizeof st[0].L, stdin)) {
    // successfully read
}

至于为数组“赋值”空值,你不能;数组不可分配。您可以通过简单地将第一个元素设为空终止符来使它们成为空字符串:

std[0].L[0] = '\0';

但是,数组永远不能为空。看起来你混淆了数组和指针。

顺便说一句,提高你的警告水平。由于格式字符串和输入类型之间不兼容,您应该在scanf次调用上遇到错误。