小编use*_*671的帖子

Python:如何停止一个函数?

例如:

def main():
    if something == True:
        player()
    elif something_else == True:
        computer()

def player():
    # do something here
    check_winner()  # check something 
    computer()  # let the computer do something

def check_winner(): 
    check something
    if someone wins:
        end()   


def computer():
    # do something here
    check_winner() # check something
    player() # go back to player function


def end():
    if condition:
        # the player wants to play again:
        main()
    elif not condition:
        # the player doesn't want to play again:
        # stop …
Run Code Online (Sandbox Code Playgroud)

python function

21
推荐指数
3
解决办法
13万
查看次数

什么时候结构没有填充?

sizeof(x) 为下面的结构返回2

struct s {
    short c;
} x;
Run Code Online (Sandbox Code Playgroud)

但对于结构

struct s {
    short c;
    char a;
} x;
Run Code Online (Sandbox Code Playgroud)

sizeof(x)回来4,为什么?

第二个获取一个填充字节(假设short为2个字节长,char为1个字节长).第一个结构不应该有2个填充字节(因此长度为4个字节)?

c

6
推荐指数
1
解决办法
89
查看次数

C - 如果达到 EOF,为什么 fread() 有两种可能的行为?

我不明白为什么函数 fread() 在这两个示例中表现不同:

1)
我有一个带有short和char的结构(大小为4个字节,包括填充)和一个由三个这样的结构组成的数组。如果我用fwrite()分别写入每个结构的每个short和char,然后用fread读取该文件() 对于一个类型为该结构的变量,我将一次读取 4 个字节(文件中将有 9 个字节),因此您可以看到在第 3 次迭代中将留下一个字节(并且在第 3 次迭代中将丢失一个字节)每次迭代)。发生的情况是没有第三次读取,因为我只剩下一个字节,而 fread 必须读取 4 个字节。

2)
一个更简单的例子,如果我使用 fwrite() 将 1 字节字符写入文件,然后使用 fread() 将该文件的内容放入 4 字节 int 中,则整数将获取该数据。

为什么会发生这种情况?如果达到 EOF,为什么在一种情况下会读取数据,而在另一种情况下却不会读取数据?

这是第一个例子:

int main()
{
    struct X { short int s; char c; } y, x[]=
    {{0x3132,'3'},{0x3435,'6'},{0x3738,'9'}};
    FILE *fp=fopen("FILE.DAT","wb+");
    if (fp)
    {
        for(int i=0;i<sizeof(x)/sizeof(x[i]);)
        {
            fwrite(&x[i].s,sizeof(x[i].s),1,fp);
            fwrite(&x[i].c,sizeof(x[i].c),1,fp);
            i++;
        }
        rewind(fp);
        for(int i=0;fread(&y,sizeof(y),1,fp);)
        printf("%d:%x %c\n",++i, y.s, y.c);
        fclose(fp);
    }
return 0;
}  
Run Code Online (Sandbox Code Playgroud)

第二个例子:

int main()
{
    FILE *fp=fopen("FILE.DAT","wb+");
    char c …
Run Code Online (Sandbox Code Playgroud)

c

2
推荐指数
1
解决办法
1201
查看次数

标签 统计

c ×2

function ×1

python ×1