标签: c11

是"返回i ++,i,i ++;" C中的未定义行为?

如果我这样写:

i = i++, i, i++;
Run Code Online (Sandbox Code Playgroud)

它是C语言中未定义的行为.

但是,如果我这样写:

return i++, i, i++; // Is it UB?
Run Code Online (Sandbox Code Playgroud)

是不确定的行为?

例:

#include <stdio.h>

int f(int i)
{
    return i++, i, i++; // Is it UB?
}
int main() {
    int i = 1;
    i = i++, i, i++;

    i = f(i);
    printf("%d\n",i);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c undefined-behavior language-lawyer c11

-2
推荐指数
2
解决办法
243
查看次数

为什么我不能将函数返回的结构分配给结构?

我编写了“轻量级”时间库,并且有如下所示的 struct 和 typedef:

struct tmt {
    uint16_t year;
    uint8_t month;
    uint8_t day;
    uint8_t hour;
    uint8_t minute;
    uint8_t second;
    uint8_t weekday;
    uint8_t is_dst; 
};

typedef struct tmt tm_t;
Run Code Online (Sandbox Code Playgroud)

我有一个返回的函数tm_t

tm_t rtc_get_current_time(void){
    tm_t tm;
    xSemaphoreTake(rtc_mutex, RTC_MUTEX_MAX_WAIT);
    tm = rtc.current_time;
    xSemaphoreGive(rtc_mutex);
    return tm;
}
Run Code Online (Sandbox Code Playgroud)

我想这样使用它:

tm_t s;
s = rtc_get_current_time();    // error is here
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

从类型“int”分配给类型“tm_t”{aka“struct tmt”}时不兼容的类型


我也尝试过像这样更改函数和变量:

struct tmt rtc_get_current_time(void){
    tm_t tm;
    xSemaphoreTake(rtc_mutex, RTC_MUTEX_MAX_WAIT);
    tm = rtc.current_time;
    xSemaphoreGive(rtc_mutex);
    return tm;
}

struct tmt tm = rtc_get_current_time();
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

c stm32 c11 cortex-m arm-none-eabi-gcc

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

图书馆在C11或C99的良好做法

什么是更好的主意:编写将在C11或C99中被其他人使用的库?许多人宁愿在CIS项目中使用C99而不是C11,这是否是正确的理由?什么对微控制器更好?我不专业,我想有充分的借口不使用通用C11:P谢谢你的帮助.我希望这不是'愚蠢'的问题.

c c99 c11

-3
推荐指数
1
解决办法
632
查看次数

写ptr =&i是否合法; 在C?

我已经使用gcc prog.c -Wall -Wextra -pedantic -std=gnu11命令在GCC上编译了以下代码.它不会产生任何警告或错误.

码:

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

int main() 
{
    int i = 10;
    int *ptr = malloc(1);

    ptr = &i; // is it legal?

    printf("%d\n", *ptr);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

显示的输出10.

这里,为ptr指针使用malloc函数分配动态内存,然后ptr保存ivarable 的地址.

ptr = &i;用C语写是否合法?

编辑:

那么,编译器是否可以生成有关内存泄漏的警告?

c malloc gcc pointers c11

-5
推荐指数
1
解决办法
164
查看次数

为什么这个程序在C11中编译好但在C99中没编译?

请考虑以下程序:(请参阅此处的实时演示).

#include <stdio.h>
struct Test
{
    int a;
};
typedef struct Test t;
typedef struct Test t;
int main()
{
    t T={9};
    printf("%d",T.a);
}
Run Code Online (Sandbox Code Playgroud)

该程序在C11编译器中编译良好,但在C99编译器中编译失败.为什么?是什么原因?我的编译器gcc 4.8.1给出以下警告:

[Warning] redefinition of typedef 't' [-Wpedantic]
[Note] previous declaration of 't' was here
Run Code Online (Sandbox Code Playgroud)

c struct typedef c99 c11

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

为什么C标准包含许多不安全的功能?

为什么C标准包含许多不安全的功能,例如,它们是无用的(在良好的程序中它们不使用)并且有害getchar?为什么C标准不包含它们的有用功能,例如getch,和getche?这只是众多例子中的一个......

UPD我很困惑:gets而不是getchar.

c c99 c89 c11

-8
推荐指数
1
解决办法
274
查看次数