考虑这个程序:
#include <stdio.h>
int main(void)
{
unsigned int a;
printf("%u %u\n", a^a, a-a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
是不确定的行为?
从表面上看,它a是一个未初始化的变量.所以这指向未定义的行为.但是a^a并且a-a等于0所有的价值a,至少我认为是这样的.有可能有某种方式来证明行为是明确定义的吗?
我是C语言编程的新手,现在我正在研究字符串.我的问题是:如果我使用malloc(如下面的代码中)分配字符串,是否在字符串的末尾自动插入NULL字符?我在这里找到另一个问题的答案,似乎不会自动包含NULL字符.但是问题就出现了:我知道strlen如果没有NULL字符,那么函数就不起作用了,在这段代码中我使用它并且它有效.所以我认为\0在我的字符串的末尾,即使我不在任何地方写它.答案是什么?
这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv) {
char *stringa1;
int n;
int i;
printf("How many characters in the string? ");
scanf("%d", &n);
stringa1 = (char*) malloc(n*sizeof(char));
printf("Insert the string: ");
scanf("%s", stringa1);
free(stringa1);
return 0;
}
Run Code Online (Sandbox Code Playgroud) 该函数strncpy()并不总是null终止所以我想知道什么是总是null终止的最佳替代?我想要一个函数,如果:
strlen(src) >= n /*n is the number of characters to be copied from source*/
Run Code Online (Sandbox Code Playgroud)
没有必要像这样添加更多代码:
buf[sizeof(buf)-1] = 0;
Run Code Online (Sandbox Code Playgroud)