小编Mud*_*ain的帖子

sizeof('\0') 空终止符作为文字是四个字节,但为什么在字符串中它只需要一个字节?

在 c 中 '\0' 空终止符作为文字需要 4 个字节(因为它内部只是零),但为什么在字符数组或字符串中使用时它只需要 1 个字节?这个编译器有魔力吗?

使用动态内存分配来处理空终止符大小时,程序员是否需要特别小心?下面的程序可以吗?

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

int main()
{
   printf("size of null-termination: %lu\n", sizeof('\0')); //outputs 4 bytes
   printf("size of 0: %lu\n", sizeof(0)); // outputs 4 bytes

   char *message = malloc(10);
   message[0] = 'A';
   message[1] = 'B';
   message[2] = 'C';
   message[3] = '\0'; // takes 1-byte in below memory layout(attached image)

   message[4] = 'a';
   message[5] = 'b';
   message[6] = 'c';
   message[7] = '\0'; // takes 1-byte in below memory layout(attached image)

   message[8] = 'X';
   message[9] …
Run Code Online (Sandbox Code Playgroud)

c malloc c-strings sizeof null-terminated

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

这是在C#.NET a ++ + ++中完美定义的吗?如果是,那为什么我会得到奇怪的输出?

我知道下面的代码会导致根据c/c ++标准的未定义行为但是在c#中呢?,经过一些搜索,我发现在c#中,表达式中的所有参数/变量都是从左到右计算的(如果错误请纠正我),如果这是真的,那么下面程序的结果(res变量的输出)应该是3,但它的4 ??

class Program
{
    static void Main(string[] args)
    {
        int a = 1;
        int res = (a++) + (++a); //Will This Lead to Undefined Behavior(Like in C/C++)..??
        Console.WriteLine(res);
        Console.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

当使用从左到右的评估检查时,结果适用于这些表达式.

res = a + ++a; \\Successfully evaluates res to 3

res = ++a + a; \\Sussessfully evaluates res to 4

res = ++a + a++; \\Successfully evaluates res to 4

同样

res= a++ + ++a ;\\should be 3, why i get it 4 ??

任何人都可以解释我的困惑.

.net c# undefined-behavior pre-increment post-increment

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

这是从头开始模拟纯 C 函数的有效方法吗?

// fakePow.c
#include <math.h>
double pow(double b, double p)
{ 
    return 6.0;
}
Run Code Online (Sandbox Code Playgroud)
//main.c
#include <stdio.h>
#include <math.h>
int twice(int x)
{
    if (x <= 0)
        return 0;

    return x * 2;
}
int main()
{
    int x = pow(10, 2);
    int res = twice(x);
    printf("%d\n", res);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

首先,我尝试了简单的编译,它不起作用,它返回200而不是12

gcc -c main.c
gcc -c fakePow.c
gcc main.o fakePow.o -o main
./main

200
Run Code Online (Sandbox Code Playgroud)

然后我用google找到了LD_PRELOAD,但它也不起作用,因为它返回200而不是12

gcc -c main.c
gcc -shared -o ./fakePow.so ./fakePow.c
LD_PRELOAD=./fakePow.so ./main

200
Run Code Online (Sandbox Code Playgroud)

c linker mocking

0
推荐指数
1
解决办法
60
查看次数