我手头有一个问题:"练习2-6.写一个函数setbits(x,p,n,y)返回x,其中n位从位置p开始设置为y的最右边n位,离开其他位不变."
我已经为此编写了一个函数,如下所示.这是按预期工作的.
int func_setx(int x,int p,int n,int y)
{
int a_t= ~0 << (p+n);
int b_t= ~a_t >> n;
int x_t= x& (a_t | b_t); // a temporary x which has the bits to be changed as 0 , rest of the bits unchanged.
int mask= (y << p) & (~(~0 << (p+n))); // a mask which has required bits from y in positions to be set , rest all bits 0.
printf("\nCheckpoint : mask= %x x_t= %x\n",mask,x_t);
int result= …Run Code Online (Sandbox Code Playgroud) 我在下面的一段代码:
float i=85.00;
printf("%f %p",i,i);
Run Code Online (Sandbox Code Playgroud)
打印o/p:
85.00000 (nil)
Run Code Online (Sandbox Code Playgroud)
但是当我改变下面的顺序时:
float i=85.00;
printf("%p %f",i,i);
Run Code Online (Sandbox Code Playgroud)
o/p是:
(nil) 0.00000
Run Code Online (Sandbox Code Playgroud)
虽然我希望类似的o/p应按照前面提到的顺序打印.有什么行为可以请任何人解释一下吗?
在我的下面的代码中,如果我声明old_act为全局变量,那么该程序工作正常.如果在main中声明:
有人可以帮我理解发生的事情.
void sighandler(int signum)
{
printf("Caught signal:%d pressed ctrl+c!!\n",signum);
}
int main()
{
struct sigaction act_h;
struct sigaction old_act;
act_h.sa_handler = sighandler;
// act_h.sa_flags = SA_RESTART;
sigaction(SIGINT,&act_h,&old_act);
printf("This is an infinite loop\n");
int remain=sleep(10);
printf("remaining time in sec : %d\n",remain);
printf("Before second sleep\n");
sleep(10);
printf("This is an infinite loop\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
从gdb看起来有些函数调用发生在非法位置,但不确定:
This GDB was configured as "i686-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/diwakar/Documents/my_C_codes/L2IT/SigHandling/a.out...done.
[New LWP 5661]
warning: Can't …Run Code Online (Sandbox Code Playgroud) 我正在学习 C 线程概念,并编写了下面的简单代码。现在,当我编译并运行它时,会出现随机行为,例如意外打印。
#include <pthread.h>
#include <stdio.h>
void * func_threadName(void * i) {
int *x=(int *)i;
printf("I'm thread : %d\n",*x);
return NULL;
}
main()
{
int iter;
printf("testing multithreading....\n");
pthread_t thread_arr[3];
for (iter=0;iter<3;iter++)
{
pthread_create(&thread_arr[iter],NULL,func_threadName,&iter);
}
for (iter=0;iter<3;iter++)
{
pthread_join(thread_arr[iter],NULL);
}
}
Run Code Online (Sandbox Code Playgroud)
它打印出不可预测的像:
diwakar@diwakar-VPCEH25EN:~/Documents/my_C_codes$ ./thread_test.o
testing multithreading....
I'm thread : 0
I'm thread : 0
I'm thread : 0
diwakar@diwakar-VPCEH25EN:~/Documents/my_C_codes$ ./thread_test.o
testing multithreading....
I'm thread : 0
I'm thread : 2
I'm thread : 1
diwakar@diwakar-VPCEH25EN:~/Documents/my_C_codes$ ./thread_test.o
testing multithreading....
I'm …Run Code Online (Sandbox Code Playgroud) 我觉得我遗漏了一些关于数字系统的基本知识,但我真的很困惑我正在尝试使用按位运算符的下面一段代码:
x=56;
printf("\nHere :\n%x %x\n",x,077);
x=x& ~077;
printf("%x\n",x);
Run Code Online (Sandbox Code Playgroud)
它将077视为八进制(hex 3f).如果我只放77,则将其视为十进制(十六进制4d).如果放177,则将其视为十进制(十六进制b1).我指的是Richie和Kernighan的C编程书.
请帮忙.