question
stringlengths
25
894
answer
stringlengths
4
863
Given two events with integer start and end times, E1 = (s1, e1), E2 = (s2, e2), implement a quick boolean check to see if the events overlap. I have the solution, but I'm curious to see what others come up with. EDIT: OK, here's my solution: ``` e1 > s2 || (s1 > s2 && e2 < s1) ```
bool overlap = (s1 <= e2) && (s2 <= e1)
I am writing C functions for Lua. I have many calls like lua_gettable, lua_touserdata, etc My C function may receive complex structures like table with tables as fields. It is hard for me to program stacked machine. Is there way to write Lua script that would be converted to C code. Or some other tools that may help me to code such C functions for lua scripts. Thanks. PS Here is example:- ``` local data = {} data.x = {} data.x.y = 1 myCfunc(data) ``` ``` int myCfunc(lua_State * L){ lua_pushstring(L, "x"); lua_gettable(L, 2); lua_pushstring(L, "y"); lua_gettable(L, -2); double y = lua_tonumber(L, -1); lua_pop(L, 2); } ``` instead of ``` function myCfunc(data) y = data.x.y end ``` My real code is much more complex and I am looking for some automated code generation that will help me.
TryLuaToCee.
Is there a way i can send a notification/message to another PC in C/C++? I think something like net send, but i don't know if there is another way to send a notification/message. I created an application which will run on every PC, and i want, that if my application has finished it should send a notification to my PC, that it has finished running. I don't know if there is a solution for my question, but if yes, could someone tell me, how to do that? Thanks, kampi
How about using sockets? http://www.alhem.net/Sockets/tutorial/
I want to copy folder A and paste to desktop. I am currently using C++ so preferably an OO interface if available.
On Windows (Win32), you could useSHFileOperation, eg: ``` SHFILEOPSTRUCT s = { 0 }; s.hwnd = m_hWnd; s.wFunc = FO_COPY; s.fFlags = FOF_SILENT; s.pTo = "C:\\target folder\0"; s.pFrom = "C:\\source folder\\*\0"; SHFileOperation(&s); ```
If you have a client/server application and you want to duplicate the same series of random numbers that the rand() function produces on the client, but on a server, what is the algorithm/pseudo code? The client and server would be given the same seed (srand() on the client). Thank you! Please note: Is this not known? If so, please stateCan it be reverse engineered? If so, please post, unless any license agreements would prevent you from doing so. In other words, don't do anything illegalI am not interested in design suggestions for the client/server applicationI understand that there are better and more recent ways to generate rand numbers
From Apple's Darwin source code,here is the Mac implementation ofrand(), which should be the same as the one used on iOS.Herealso is therandom()implementation. They both appear to be drawn from FreeBSD.
I am currently running a Lua script with a hook attached usingLUA_MASKCALLand the hook function implemented as follows: ``` void LuaHook(lua_State *L, lua_Debug *ar) { switch(ar->event) { case LUA_HOOKCALL: lua_getinfo(L, ">n", ar); //breakpoint here... } break; default: break; } } ``` I would like to get the name of the called function, but am not sure I am doing it correctly since it never seems to give me anything (the breakpoint is hit at the appropriate times though). The functions that are called are bound C functions that do have names so that seems weird. Overalllua_getinfois a complete mystery to me and the documentation does not clear things up either so any help would be greatly appreciated on this one.
lua_getstackdid the trick so never mind
There is a Ruby process and has a string var named "switch", and the "switch" will be updated by user. There are also 2 C daemon process, which need to access the "switch" in a loop and decide the logic in runtime, how to deal with this case ? thanks!
A socket (or a common file) can be used as a pipe between them.
This was my previous question: Can someone give me simple example in C, of usingpipe()system call to and use ssh to connect to a remote server and execute a simplelscommand and parse the reply. Thanks in advance, [...] I got an answer for that, but I need something more. I would like to ask how to use a pipe and connect to a remote server using ssh, then open mysql and execute a simple query likeSELECT * FROM tables;. Thanks in advance!
Are you doing this for a challenge?, if yes that's cool because you are doing a hard thing to the end, if notderobertsuggestion is the best solution in case you want to communicate with the MySQL server.
I remember having read a very good guide to writing collections. By that I mean, it described using macros to generate types with type parameters, kind of like C++ templates. I'm not sure if it was written by Rusty Russell, but it was someone I recognized. It was posted on hackernews or proggit... I wanted to write a new C library and has searched google for the past 30 min for this guide to no avail. Anybody remember?
This guide fits your description: Collections in Cby Armin Ronacher.
if anyone could answer me why this works, it would be greatly appreciated. The exercise (chapter 4, ex 7 and 8) says that if you have the expression: 9 - ((total - 1) % 10) then, you could be tempted to simplify it like this: 10 - (total % 10) But this would not work. Instead he offers the alternative: (10 - (total % 10)) % 10 Now, I understand how he got to the first simplification, but not why it's wrong, or why does the second one works. Thanks in advance
x %m has a range of (-m, m) in most C implementations. Mathematically it is generally defined from (0, m). Hence by adding m the modulo again will convert the C to the mathematical one.
The reason I'm asking: ``` #include <string.h> using namespace std; int main() { unsigned char file[512000]; unsigned char key[512000]; for(int i = 0; i < 512000; i++) file[i] = key[i]; return 0; } ``` When I compile this with cl.exe on windows I get an executable that is about 31kb in size. The buffers themselves are 500kb each. How does this make sense? Will part of it be allocated on the heap? If I initialized them with data then would the size be correct?
In this case, the buffers will be allocated on the program'sstack spaceat runtime. There's no need for them to be statically built into theexefile.
Given two events with integer start and end times, E1 = (s1, e1), E2 = (s2, e2), implement a quick boolean check to see if the events overlap. I have the solution, but I'm curious to see what others come up with. EDIT: OK, here's my solution: ``` e1 > s2 || (s1 > s2 && e2 < s1) ```
bool overlap = (s1 <= e2) && (s2 <= e1)
I want to make console window with a functional tray icon. I figured out that most probably it is necessary to replace initial console's window procedure so I will be able to control all messages including notify area events. ButSetWindowLong()function returns 0, andGetLastError()tells that access is denied. ``` hwndFound = GetConsoleWindow(); SetWindowLong(hwndFound, GWL_WNDPROC, (long)WndProc); ``` What could it be, or maybe there is some other way to control tray icon manipulations?
If all you want to do is create a notification icon for a console application, there's nothing that says your Shell_NotifyIcon call has to point to the console window. Create an invisible dummy window with your own window class and procedure instead. Note that you'll probably have to do this from a secondary thread in order to run its message loop. (The console window is special, as it's hosted outside your process by conhost.exe/csrss.exe.)
This question already has answers here:Closed11 years ago. Possible Duplicate:What does 'unsigned temp:3' mean? please what does this notation mean int a:16; I found it is code like this and it does compile. struct name { int a:16; }
This is abitfield. This particular bitfield doesn't make much sense as you just could use a 16-bit type and you're wasting some space as the bitfield is padded to the size ofint. Usually, you are using it for structures that contain elements of bit size: ``` struct { unsigned nibble1 : 4; unsigned nibble2 : 4; } ```
This question already has answers here:Closed12 years ago. Possible Duplicates:Output of multiple post and pre increments in one statementPost-increment and pre-increment in 'for' loop The following code snippet ``` int i=0; printf("%d %d",i++,i++); ``` gives the output 1 0 I can understand that, but the following ``` int i=0; printf("%d %d",++i,++i); ``` gives the output 2 2 Can someone explain me the second behavior?
Both printfs invoke undefined-behavior. See this :Undefined behavior and sequence points Quoted from this link: In short, undefined behaviour means anything can happen from daemons flying out of your nose to your girlfriend getting pregnant. For newbies :Don't ever try to modify values of your variablestwice or morein a function call argument-list. For details,click hereto know what it means. :-)
How can I invoke crypt(3) from a c program on a windows platform? I can't find a header file to include. I have MinGW with gcc and msys installed. Edit: as an alternative, I would also accept a way to call this function (or an equivalent) from Visual Studio.
Have you seen this?http://sourceforge.net/projects/mingw/files/MSYS/crypt/ I suppose you may be missing it, or just don't realize you have it, but it seems like the answer, and I found it by typing "crypt mingw" into Google.
I know thatEOFand'\0'are of type integers, but if so shouldn't they have a fixed value? I printed both and got -1 forEOFand 0 for'\0'. But are these values fixed? I also had this ``` int a=-1; printf("%d",a==EOF); //printed 1 ``` Are the value forEOFand'\0'fixed integers?
EOFis a macro which expands to an integer constant expression with typeintand an implementation dependent negative value but is very commonly -1. '\0'is acharwith value 0 in C++ and anintwith the value 0 in C. The reason whyprintf("%d",a==EOF);resulted in1was because you didn't assign the valueEOFtoa. Instead you checked ifawas equal toEOFand since that was true (a == -1 == EOF) it printed1.
This question already has answers here:Closed12 years ago. Possible Duplicate:Are nested functions a bad thing in gcc ? As far as I know, C does not allow a function to be defined within other function. But the following code compiles and runs without any error in gcc. Can someone explain the reason why? See this also :http://ideone.com/AazVK ``` #include <stdio.h> void val1( int x ) { void sig( int x ) { printf("%d\n",x*10); } sig(x); } int main() { void val2(int x) { x = x*10; val1(x); printf( "%d\n", x ); if ( x < 10000 ) { val2(x); } } val2(20); return 0; } ```
gcc(but notg++) supportsnested functionsas aC language extension.
This question already has answers here:Closed10 years ago. Possible Duplicate:Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it For example if i give a input as "This is a string" I should get the output as "string a is This" I cant get any idea on how to do it
First Reverse the string in place Then Reverse each word in place (words are delimited by a space)
binary tree, where each node has at most two child nodes, child nodes may contain references to their parents. we do not differentiate the nodes and all nodes are considered identical.How can we find the number of different binary trees that can be formed with N identical nodes. eg: if 3 nodes then 5 diff treesif 7 nodes then 429 trees
Now, if you really want to understand this, instead of just getting (or experimenting to find) the answer, you can check out "The Art of Computer Programming", Volume 4, Fascicle 4:Generating all trees.
I am trying to create a mini task manager where I can show all the process and details. I am able to get all the details by using CreateToolhelp32Snapshot, OpenProcess etc. Now for GUI I am not sure what to use? I can use windows form or windows APIs. Windows forms can make my job easier but I read somewhere that windows form won't work with win apis We can't mix managed and unmanaged code(I am not sure. I don't understand much of this). Can anybody guide me what to do in this? Can I use the forms or I can only use APIs. Is there any better way of doing this, kindly help me. Thanks in advance.
You can use both together. Simply choose what you you are familiar with. The goal is to make it done and working, isn't it? :-)
To move objects with a variable time step I just have to do: ``` ship.position += ship.velocity * deltaTime; ``` But when I try this with: ``` ship.velocity += ship.power * deltaTime; ``` I get different results with different time steps. How can I fix this? EDIT: I am modelling an object falling to the ground on one axis with a single fixed force (gravity) acting on it.
``` ship.position = ship.position + ship.velocity * deltaTime + 0.5 * ship.power * deltaTime ^ 2; ship.velocity += ship.power * deltaTime; ``` http://www.ugrad.math.ubc.ca/coursedoc/math101/notes/applications/velocity.html The velocity part of your equations is correct and they must both be updated at every time step. This all assumes that you have constant power (acceleration) over the deltaTime as pointed out by belisarius.
I have some code, that I'm currently porting from OS X to Linux (console tool). Somewhere in this code, I get a segmentation fault. The problem is, that if I run the program without GDB, I clearly see the segmentation fault, and the program is killed. But when I'm running GDB it just halts, and GDB never returns to the prompt. So I'm not really able to examine what's going on. C++ is the code. Compiled with the -g option in g++. Btw. Pretty new to GDB, so excuse me if this is obvious. Any ideas? Thanks in advance. Trenskow
gdb will suspend your program when the seg fault signal is received typewhereto see the stack trace and start inspecting what's going on from there. Also consider enabling core dumps, that way you can load the core dump in GDB and investigate what is going on you can then load the core dump like this > gdb your_program the_core_dump
I want to make console window with a functional tray icon. I figured out that most probably it is necessary to replace initial console's window procedure so I will be able to control all messages including notify area events. ButSetWindowLong()function returns 0, andGetLastError()tells that access is denied. ``` hwndFound = GetConsoleWindow(); SetWindowLong(hwndFound, GWL_WNDPROC, (long)WndProc); ``` What could it be, or maybe there is some other way to control tray icon manipulations?
If all you want to do is create a notification icon for a console application, there's nothing that says your Shell_NotifyIcon call has to point to the console window. Create an invisible dummy window with your own window class and procedure instead. Note that you'll probably have to do this from a secondary thread in order to run its message loop. (The console window is special, as it's hosted outside your process by conhost.exe/csrss.exe.)
This question already has answers here:Closed11 years ago. Possible Duplicate:What does 'unsigned temp:3' mean? please what does this notation mean int a:16; I found it is code like this and it does compile. struct name { int a:16; }
This is abitfield. This particular bitfield doesn't make much sense as you just could use a 16-bit type and you're wasting some space as the bitfield is padded to the size ofint. Usually, you are using it for structures that contain elements of bit size: ``` struct { unsigned nibble1 : 4; unsigned nibble2 : 4; } ```
This question already has answers here:Closed12 years ago. Possible Duplicates:Output of multiple post and pre increments in one statementPost-increment and pre-increment in 'for' loop The following code snippet ``` int i=0; printf("%d %d",i++,i++); ``` gives the output 1 0 I can understand that, but the following ``` int i=0; printf("%d %d",++i,++i); ``` gives the output 2 2 Can someone explain me the second behavior?
Both printfs invoke undefined-behavior. See this :Undefined behavior and sequence points Quoted from this link: In short, undefined behaviour means anything can happen from daemons flying out of your nose to your girlfriend getting pregnant. For newbies :Don't ever try to modify values of your variablestwice or morein a function call argument-list. For details,click hereto know what it means. :-)
How can I invoke crypt(3) from a c program on a windows platform? I can't find a header file to include. I have MinGW with gcc and msys installed. Edit: as an alternative, I would also accept a way to call this function (or an equivalent) from Visual Studio.
Have you seen this?http://sourceforge.net/projects/mingw/files/MSYS/crypt/ I suppose you may be missing it, or just don't realize you have it, but it seems like the answer, and I found it by typing "crypt mingw" into Google.
I know thatEOFand'\0'are of type integers, but if so shouldn't they have a fixed value? I printed both and got -1 forEOFand 0 for'\0'. But are these values fixed? I also had this ``` int a=-1; printf("%d",a==EOF); //printed 1 ``` Are the value forEOFand'\0'fixed integers?
EOFis a macro which expands to an integer constant expression with typeintand an implementation dependent negative value but is very commonly -1. '\0'is acharwith value 0 in C++ and anintwith the value 0 in C. The reason whyprintf("%d",a==EOF);resulted in1was because you didn't assign the valueEOFtoa. Instead you checked ifawas equal toEOFand since that was true (a == -1 == EOF) it printed1.
This question already has answers here:Closed12 years ago. Possible Duplicate:Are nested functions a bad thing in gcc ? As far as I know, C does not allow a function to be defined within other function. But the following code compiles and runs without any error in gcc. Can someone explain the reason why? See this also :http://ideone.com/AazVK ``` #include <stdio.h> void val1( int x ) { void sig( int x ) { printf("%d\n",x*10); } sig(x); } int main() { void val2(int x) { x = x*10; val1(x); printf( "%d\n", x ); if ( x < 10000 ) { val2(x); } } val2(20); return 0; } ```
gcc(but notg++) supportsnested functionsas aC language extension.
This question already has answers here:Closed10 years ago. Possible Duplicate:Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it For example if i give a input as "This is a string" I should get the output as "string a is This" I cant get any idea on how to do it
First Reverse the string in place Then Reverse each word in place (words are delimited by a space)
binary tree, where each node has at most two child nodes, child nodes may contain references to their parents. we do not differentiate the nodes and all nodes are considered identical.How can we find the number of different binary trees that can be formed with N identical nodes. eg: if 3 nodes then 5 diff treesif 7 nodes then 429 trees
Now, if you really want to understand this, instead of just getting (or experimenting to find) the answer, you can check out "The Art of Computer Programming", Volume 4, Fascicle 4:Generating all trees.
I am trying to create a mini task manager where I can show all the process and details. I am able to get all the details by using CreateToolhelp32Snapshot, OpenProcess etc. Now for GUI I am not sure what to use? I can use windows form or windows APIs. Windows forms can make my job easier but I read somewhere that windows form won't work with win apis We can't mix managed and unmanaged code(I am not sure. I don't understand much of this). Can anybody guide me what to do in this? Can I use the forms or I can only use APIs. Is there any better way of doing this, kindly help me. Thanks in advance.
You can use both together. Simply choose what you you are familiar with. The goal is to make it done and working, isn't it? :-)
To move objects with a variable time step I just have to do: ``` ship.position += ship.velocity * deltaTime; ``` But when I try this with: ``` ship.velocity += ship.power * deltaTime; ``` I get different results with different time steps. How can I fix this? EDIT: I am modelling an object falling to the ground on one axis with a single fixed force (gravity) acting on it.
``` ship.position = ship.position + ship.velocity * deltaTime + 0.5 * ship.power * deltaTime ^ 2; ship.velocity += ship.power * deltaTime; ``` http://www.ugrad.math.ubc.ca/coursedoc/math101/notes/applications/velocity.html The velocity part of your equations is correct and they must both be updated at every time step. This all assumes that you have constant power (acceleration) over the deltaTime as pointed out by belisarius.
Is there a way to convert a hexdump e.g. aec4d2f3c6a4e70ea6cea074f65812d2a34b180cc92b817edcd867167e7a91c5beb942f0 to a string in c so that every two hexadecimal digits make a char? If so, what?
Reads from stdin and prints to stdout: ``` int main() { int ch; while(scanf("%2x", &ch) == 1) putchar(ch); } ``` I think you can modify it easily yourself for your specific source and destination requirements.
In the given code snippet, I expected the errorsymbol Record not found. But it compiled and ran fine on Visual Studio 2010 Compiler. I ran it as a C program from Visual Studio 2010 Command Prompt in the manner - cl Record.cRecord Now the doubt is, doesn'ttypedefcheck for symbols ? Does it work more like aforward declaration? ``` #include "stdio.h" #include "conio.h" typedef struct Record R; struct Record { int a; }; int main() { R obj = {10}; getch(); return 0; } ```
You can always refer to undefined structures, which is a typical way to implement linked lists, after all. They just have to be defined when you want to make use of their fields.This pagecontains some details.
is it possible to get just one bit of an int in C and then flip it without reading the entire int and writing it back to memory? context: trying to avoid too many locks/unlocks in pthread.
You can not read a single bit from the memory, actually you can not force CPU to read only a single byte. It is always reading a full cache line, which could have different sizes for different CPUs. But from the language point of view you can use bit fieldshttp://publications.gbdirect.co.uk/c_book/chapter6/bitfields.html
I've read aboutSetScrollRangebut still didn't get what the range (min, max) is in scrollbar. I've set the rich edit control's vertical scroll bar range to (0, 100) ``` SetScrollRange(hwndRichEditControl, SB_VERT, 0, 100, TRUE); ``` Now, If I tryGetScrollPosto get the position i'm getting the value over max range. Shouldn't the position be between 0 and 100? ``` int Pos = GetScrollPos(hwndRichEditControl, SB_VERT); ```
It shouldn't. The RichEdit control itself determines the scroll range of the scroll bar. Which it does depending on how much text it displays. Overriding it isn't going to last long, if at all. You can only use GetScrollInfo() to find out what it is using currently. This is going to change as soon as the user adds text.
I'm running throughtheForger's Win32 API Programming Tutorial. Onpage 4he suggests it would be handy to find the list of #define statements in the API header files which list all the WM_* messages. I decided it probably would be worth my while to take a gander at them all, so I tried to find them, but was unsuccessful. If anyone could just send the name of the appropriate file and possibly its location relative to "windows.h" my way, it would be much appreciated. I have been rummaging around in my compiler's "include" folder for quite a while now, and for the life of me I can't find it, so I figured before I go ahead and look at every single include file (there are 294 of them), I should ask you guys, since I'm sure someone knows already. Thanks in advance.
Trywinuser.hin the platform SDK include folder.
I am checking to make sure a float is not zero. It is impossible for the float to become negative. So is it faster to do thisfloat != 0.0for thisfloat > 0.0f? Thanks. Edit: Yes, I know this is micro-optimisation. But this is going to be called every time through my game loop, and I would like to know anyway.
There is not likely to be a detectable difference in performance.
0x7F000000is0111 1111 0000 0000 0000 0000 0000 0000in 32 bit binary.0x01000058is0000 0001 0000 0000 0000 0000 0101 1000. When I AND the two numbers together I expect0000 0001 0000 0000 0000 0000 0000 0000, but for some reason I get 0. Here is my code: ``` #define MASK_binop 0x80000000 #define MASK_operation 0x7F000000 int instruction=atoi(line); if((MASK_binop & instruction)>0) printf("binop\n"); else if((MASK_operation & instruction)>0) printf("operation\n"); ``` Each of the above comparisons keeps returning zero. Is it something to do with 32/64 bits? I'm using 64-bit compiler.
If line contains "0x01000058" then atoi will return 0 as atoi works with decimal representation, not hex 0x representation. And then the AND obviously is zero. Try to printf the value of instruction.
I have a 32 bit integer, split into parts like this: ``` -------------------------------------- | Part1 | Part2 | Part 3 | -------------------------------------- ``` Part 1 higher 16 bits. (Part 2 + Part 3) = lower 16 bits. Part 2 is 10 bits and Part 3 is 6 bits I need help on how do we read and update part 1, part2 and part 3 in C program.
Given an integerxwith the above format, you can replace Part2 like this: ``` x = (x & ~(0x3ff << 6)) | (newPart2 << 6); ``` and Part3 like so: ``` x = (x & ~0x3f) | newPart3; ``` This assumes that bothnewPart2andnewPart3are e.g.unsigned intwith their new values right-adjusted.
Does anybody experience mixing -g (debugging symbols) and -O2 (best safe optimization) with gcc compiler?I have to debug crashes of a release program distributed to final users that could send me back the core file.I've always used to call: gdb << myprogram >> << core file >> and see where the trouble is. Now I can just see the call-trace but having no debugging symbols I'm quite in trouble. Any idea?
It works fine. Or well, due to the optimization sometimes the source you're stepping through with the debugger doesn't match up exactly with the source, but IMHO despite this having the debug symbols makes debugging much easier.
This question already has answers here:Closed11 years ago. Possible Duplicate:How do you read C declarations? I Don't understand the following: ``` int‬‬ ‪* (*(*p)[2][2])(int,int); ``` Can you help?
For things like this trycdecl, decoded to; ``` declare p as pointer to array 2 of array 2 of pointer to function (int, int) returning pointer to int ```
``` valgrind-3.6.0.SVN-Debian gcc (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5 2.6.35-22-generic ``` I am using valgrind to detect memory errors in our code. However, are application uses some third party libraries (shared library). When we start to capture using valgrind. It goes into this library, and displays many memory errors with this library. So it is difficult to check our application due to this. There is many to go through. It is possible to configure valgrind to only check our source code and not go into the shared libraries? Is there any other open source memory checking software that can do this if valgrind cannot? Many thanks for any suggestions,
You can try suppressing the errors generated by the library code: http://valgrind.org/docs/manual/manual-core.html#manual-core.suppress
Why is thetimefunction usually used like this: ``` time_t currentTime; currentTime = time( NULL ); ``` instead of this: ``` time_t currentTime; time( &currentTime ); ``` Is the first method used more just because it is arguably more readable? Or is there another reason? Thanks. Edit: Also, why was thetimefunction even designed this way? Why have two ways to set the variable?
It always seems to make more sense to return a value from a function than pass a paramter that is changed. This might be because we learned on languages where functions and subroutines were different, don't know about these youngsters today.
This question already has answers here:Closed12 years ago. Possible Duplicate:How to write program during compiling? I found this problem on a site full of interview questions, and was stumped by it. Is there some preprocessor directive that allows one to read from standard input during compilation? Write a small C program, which while compiling takes another program from input terminal, and on running gives the result for the second program. (NOTE: The key is, think UNIX). Suppose, the program is 1.c Then, while compiling ``` $ cc -o 1 1.c int main() { printf("Hello World\n"); } ^D $ ./1 Hello World ``` EDITIt turns out this question is an exact duplicate.How to write program during compiling?
#include "/dev/stdin"is the trick. A silly interview question at best.
``` struct A { int member1; int member2; struct B { int member3; int member4; } *b; }; ``` How can I initializeAand at the same time create an array ofB's to fill thebfield? I want a static variable, so preferably function calling. I tried this but it does not work (I didn't think it would): ``` static A a = { 1, 2, & { {3, 4}, {5, 6} }, } ```
I think the problem with this code is this line: ``` & { {3, 4}, {5, 6} } ``` The problem is that{{3, 4}, {5, 6}}is an rvalue (a value, not an object) and you can't take the address of an rvalue. After all, where is the memory for this object going to come from? However, you might be able to get away with rewriting this to ``` A::B elems[2] = {{3, 4}, {5, 6}}; static A a = { 1, 2, elems }; ``` Since now you have an lvalue you can point at.
Is there a way to test for the existence of C functions in Objective-C? I'm looking for something like "respondsToSelector," but for C functions. More specifically, I'm trying to test for the existence of "UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque>, CGFloat scale)" in iOS. Thanks.
``` if(&UIGraphicsBeginImageContextWithOptions != NULL) UIGraphicsBeginImageContextWithOptions(); else NSLog(@"No UIGraphicsBeginImageContextWithOptions function"); ```
I am working on a moderately large C file where I need to do processing for 3 different exclusive conditions. (if condition 1 is present do this, if 2 is present do something else and likewise). So, at many places in that file, I need to do if/else checks - which looks dirty. I have some 50 places where I am doing these checks. Is there a better way, to make code look cleaner?
If the conditions are really exclusive then I'd start with three separate functions, one for each process. Break any common code out into their own functions that you can call from the three process functions. The only conditional left should be where you decide which of the three process functions to call.
In the C programing language, why do the bitwise operators (& and |) have lower precedence than the equality operator (==)? It does not make sense to me.
You need to ask Brian Kernighan or Dennis Ritchie.From this forum:http://bytes.com/topic/c/answers/167377-operator-precedence The && and || operators were added later for their "short-circuiting" behavior. Dennis Ritchie admits in retrospect that the precedence of the bitwise operators should have been changed when the logical operators were added. But with several hundred kilobytes of C source code in existence at that point and an installed base of three computers, Dennis thought it would be too big of a change in the C language... So, that might be a reason? I'm guessing since there are several layers of bitwise precendence (unlike relational comparisons) that it's cruft that's existed since...forever...and just was never corrected.
So I have compiled a small testing program that uses SWIG as a bridge between python and C. The main part of the program is the python file. The thing runs fine on my own pc, but as soon as I transfer it to another, it immediately throws a "ImportError: DLL load failed: The specified module could not be found." error. I tried to see if it could be a file location that was statically coded by moving it to another directory on my own pc, which still worked fine. Next I did some debugging in the SWIG python wrapper, and found out what DLL it was loading; whose file path was correct too. My other PC also had the correct path. Does anyone know something that I might have forgotten that causes this error?
Everyone having this problem should probably check out thedependency walker, and see what DLLs are missing. It solved my problem.
I'm looking for a library in c or objective c that does node-data visualizations similar tohttp://arborjs.org/ helpful answers include, what are graphs like that called?names of libraries that do something like that.suggestions for implementation. I'm targeting iOS and/or MacOS, hence c or objective-c/cocoa. On iOS the javascript version runs super slow. Thanks! Edit: GraphViz looks great. I'm a little concerned it may have dependencies that are GPL, and thus can't be used on iOS... looking into that now.
Actually there seems to be an Objective-C port of arborjs, seehttps://github.com/epreston/PSArborTouch.
This question already has answers here:Closed12 years ago. Possible Duplicate:function overloading in C So I wonder if we can use something likevoid A(){}andvoid A(int b){}in same code file?
That's not functionoverriding, but functionoverloading. Anyway no, C doesn't provide it. The rationale (well, one of them, the one I prefer) is that to provide function overloading you should find a way to give a symbol to a function based also on its parameters, not only on its name.This would cause a few problems that a low-level language as C wouldn't take.
Is there a hack to support range case in a c(99?) or objective C switch statement ? I know this is not supported to write something like this: ``` switch(x) case 1: case 2..10: case 11: ``` But I was thinking there should be a way to generate code with a #define macro. Of course I can define a macro with the list of cases but I was hoping for a more elegant way like CASERANGE(x,x+10) which would generate: ``` case x case x+1 case x+2 ``` is it even possible ?
GCC has anextension to the C languagethat allows something similar to your first example, but other than that, if there was a portable/ANSI way of doing it, it would have been done by now. I don't believe there is one.
Why do the variables take garbage values?
I guess the rationale for this is that your program will be faster. If compiler automaticallyreset(ie: initialize to 0 or to NaN for float/doubles etc etc) your variables, it would take some time doing that (it'd have to write to memory).In many cases initializing variables could be unneeded: maybe you will never access your variable, or will write on it the first time you access it. Today this optimization is arguable: the overhead due to initializing variables is maybe not worth the problems caused by variables uninitialized by mistake, but when C has been defined things were different.
What is the difference between ``` int* a = 0; ``` and ``` int* a = 10; ``` ?
int* adeclares variableaas a pointer to integer. =0and=10assign some value to the variable. Note thatais a pointer, its value is supposed to be an address. Address0has a particular meaning: it'sNULL, represent anemptypointer.Address10has no meaning: it's a random memory address. Since it's notNULL, most functions will consider it a valid address, will dereference it, and thus it will create problems (undefined behavior) to your application.
``` #include<stdio.h> double i; int main() { (int)(float)(char) i; printf("%d", sizeof((int)(float)(char)i)); return 0; } ``` The above outputs 4 on a Micrsoft compiler. Why?
sizeofis the size, in bytes, of the variable. In this case,iis being cast to anintwhich is 4 bytes. These are the sizes of types on MS C++:http://msdn.microsoft.com/en-us/library/cc953fe1(v=vs.71).aspx
Where are the Python bindings, or what is the current status of thePython bindingsforGIO'sGSocketand otherlowlevel network support?
The Gnome documentation is known to be somewhat not up to date. One may endlessly say words like community, manpower, time, effort, et cetera. The fact is that when you do ``` >>> import gio >>> help(gio.Socket) ``` you will see that the class is there (and others too). That is just the doc missing its description. I suggest in this case the best choice would be to rely on python's inline doc system.
I did this: ``` import cStringIO.StringIO as StringIO ``` And I realize I've been using it everywhere. Is that fine? Is it treated the same as StringIO?
They are not the same.cStringIOdoesn't correctly handle unicode characters. ``` >>> StringIO.StringIO().write(u'\u0080') >>> cStringIO.StringIO().write(u'\u0080') Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode character u'\x80' in position 0: ordinal not in range(128) ```
Is there a stable library that can validate JSON against aschema? json-schema.orgprovides alist of implementations. Notably C and C++ are missing. Is there a reason I can't easily find a C++ JSON schema validator?Doesn't anyone else want a quick way to validate incoming JSON files?
Is there a stable library that can validate JSON against a schema? I found a couple hits on google: From the Chromium project:http://aaronboodman-com-v1.blogspot.com/2010/11/c-version-of-json-schema.htmlhttp://avro.apache.org/docs/1.4.1/api/cpp/html/index.html You could also plug a Python or Javascript interpreter into your app, and simply run the native version of those validator implementations that you've already found. Is there a reason I can't easily find a C++ JSON schema validator? I believe JSON originated as a web technology, and C/C++ has fallen out of favor for web app implementation.
I write a struct ``` struct Tree{ struct Node *root; struct Node NIL_t; struct Node * const NIL; //sentinel } ``` I want ``` struct Node * const NIL = &NIL_t; ``` I can't initialize it inside the struct. I'm using msvs. I use C, NOT C++. I know I can use initialization list in C++. How to do so in C?
If you are using C99, you can used designated initializers to do this: ``` struct Tree t = { .root = NULL, .NIL = &t.NIL_t }; ``` This only works in C99, though. I've tested this on gcc and it seems to work just fine.
I have two threads, communicating with each other; each thread employs 'while(1) ..'. Now I need to let the threads exit upon a specific condition met, and therefore finish the application. My question: is it safe to just 'return (NULL)' from the thread, or do I have to use 'pthread_exit' or 'pthread_join' functions as well?
It is safe to return null from the thread functions; the code that waits for them should be OK. POSIX says ofpthread_exit(): An implicit call to pthread_exit() is made when a thread other than the thread in which main() was first invoked returns from the start routine that was used to create it. You do need something to wait for the thread withpthread_join()unless the thread was created with the detached attribute or detached later withpthread_detach().
The general strategy for boost file locking (sharable and scoped file_locks), and file locking in general I think, is this: openlockoperate on file contentsunlockclose the file However, I will be opening the file for append and want to call tellp to see where I am. Is this safe to do in the above scenario? Won't the file pointer be set as soon as the file is opened before the lock and thus potentially not protected? If so, is there a standard idiom to get around this?
This may be environment-specific, but on the majority of platforms: When a file is opened for append the file pointer is adjusted immediately before every write. So, if you usetellpbefore locking the file, it might not tell you where your newly appended bytes are going to go, but you shouldn't have two processes using locking somehow still appending the same range of bytes.
I was wondering what is the difference between these two lines of code? ``` int hi; int *hi; ``` In the C programming language? Thanks! Amit
``` int hi; ``` reserves the space for anintin memory, and each time you referencehi, you either read or write directly thatintin memory space. ``` int *hi; ``` reserves the space for apointerto anintin memory, each timehiis used, the pointer is either read or written. Meaning that you arenotworking with anint, only a pointer to anint- there must exist anintsomewhere for the pointer to reference something workable. For instance ``` int hi; int *phi; phi = &hi; // phi references the int hi *phi = 3; // set `hi` to 3 ```
SDL_Eventis a union of an unsigned 8 bit type, and many structs whose first element is an unsigned 8 bit type. The reccomended usage is to access the Uint8 element of the union to determine what type the event is, and then access the union by the element appropriate to that type. This obviously depends on all of the types in the union having the same space reserved for the type identifier. Can we be sure this is the case, or is this undefined behavior? Edit: made the title more descriptive.
The first element of a struct is guaranteed to be at "offset 0" from the struct's beginning. So it should be safe.
The following C/C++ code results in an Unused Entity Issue with XCode 4 (Clang LLVM). ``` void stringMethod(const char *string){ while(*string!=0){ *string++; //... } } ``` Its on that line: *string++; so it seems like clang didnt realize that the pointer address is increased? I don't get, how to adjust this code... Any ideas?
Try to remove the dereferencing operator*, you don't need to dereference the pointer when you increase it.
With C/ C++,getopt_long()can be used to parse command line arguments. Is it possible to tell the function that some of the options are mandatory? For example, how can I tellgetopt_longthat the parsing should give error ifstartServeris called without mentioning the port below? ./startServer -port 80 Note: I am not talking of option arguments as mandatory but rather the options themselves.
getopt_long()is not part of the C language. It is a GNU invention which is available in some C implementations, but far from all. The version ofgetopt_long()in glibc (used in most Linux distributions) does not allow you to specify that an option is mandatory. You'll have to check them explicitly after you're done parsing the command line.
I would like to port a program which is using urllib and json (Python 3) to C. My question is which libraries exist to replace urllib and json in C and which are the best (easier, documented, fast)? If there are not good libraries in C I also accept C++ Thank you all.
For JSON,json.orghas a list of implementations for a variety of languages, including C. Most of them should be fairly lightweight and fast. To replace urllib, you probably want to look atlibcURL.
``` int i; // A. extern int i; // B. ``` I know A is a variable's definition. Namely, the compiler creates an object and assigns a block of memory to the variablei. But what is B? What's the difference between the definition and the declaration?
It's a declaration. It says there is an integerithat will be defined elsewhere.
Consider that my system has memory, but it is scattered in different places (fragmented). There are no four contiguous memory locations that are free. In that scenario, if I declare a character array of size 10 in the C language, what will happen ?
If"my system has memory, but it is scattered in different places(fragmented)"means, thatheap virtual memoryis fragmented, and"declare a character array of size 10"means, that you create character array of size 10 instack memory: ``` char str[10]; ``` , then array will be successfully created. If"declare a character array of size 10"means, that you allocate memory with malloc() (allocate in heap): ``` char *str2; str2 = (char*) malloc(10 * sizeof(char)); ``` , then malloc() will return NULL.
I tried the code in my system. This is what I got...... 1) ``` #include <stdio.h> int main() { //int a = 10; printf("%s"); return 0; } Output: 1í^áäðPTRhh ``` 2) ``` #include <stdio.h> int main() { int a = 10; printf("%s\n"); return 0; } Output: __libc_start_main ``` I tried in another system( diff compiler). And the output was different. Actually it must be printing the topmost value in the stack. Then y isn't unique everywhere?
You're dealing withundefined behavior, so you can't expect it to be consistent, nor follow any kind of pattern across compilers, architectures or even runs of the same program.
I want to include an IP packet in Socket programming. I have a readymade Ip packet which contains igmp packet. I don't want to design igmp protocol but want to use that packet to sent igmp query. By some how the Ip packet I have must be recognize as IP packet and not as TCP/UDP data.
You have to usethe raw socketwithsendmsg. This needrootpermission.
What is a good way to create a three-state Boolean in a C-based language?
While others have offered answers, I'd like to offer a justification for the best one. Use integer values -1/0/1 (or really, any negative/zero/positive). With this scheme, there is an extremely efficient check for any subset of possible values: ``` (x<0) /* {-1} */ (!x) /* {0} */ (x>0) /* {1} */ (x<=0) /* {-1,0} */ (x) /* {-1,1} */ (x>=0) /* {0,1} */ ``` On x86, all of these will compile to a singletestopcode followed by a conditional jump opcode with the appropriate conditions. If you want to hide the implementation, you can use predicate macros for testing each of the 6 subsets.
I was wondering what is the difference between these two lines of code? ``` int hi; int *hi; ``` In the C programming language? Thanks! Amit
``` int hi; ``` reserves the space for anintin memory, and each time you referencehi, you either read or write directly thatintin memory space. ``` int *hi; ``` reserves the space for apointerto anintin memory, each timehiis used, the pointer is either read or written. Meaning that you arenotworking with anint, only a pointer to anint- there must exist anintsomewhere for the pointer to reference something workable. For instance ``` int hi; int *phi; phi = &hi; // phi references the int hi *phi = 3; // set `hi` to 3 ```
SDL_Eventis a union of an unsigned 8 bit type, and many structs whose first element is an unsigned 8 bit type. The reccomended usage is to access the Uint8 element of the union to determine what type the event is, and then access the union by the element appropriate to that type. This obviously depends on all of the types in the union having the same space reserved for the type identifier. Can we be sure this is the case, or is this undefined behavior? Edit: made the title more descriptive.
The first element of a struct is guaranteed to be at "offset 0" from the struct's beginning. So it should be safe.
The following C/C++ code results in an Unused Entity Issue with XCode 4 (Clang LLVM). ``` void stringMethod(const char *string){ while(*string!=0){ *string++; //... } } ``` Its on that line: *string++; so it seems like clang didnt realize that the pointer address is increased? I don't get, how to adjust this code... Any ideas?
Try to remove the dereferencing operator*, you don't need to dereference the pointer when you increase it.
With C/ C++,getopt_long()can be used to parse command line arguments. Is it possible to tell the function that some of the options are mandatory? For example, how can I tellgetopt_longthat the parsing should give error ifstartServeris called without mentioning the port below? ./startServer -port 80 Note: I am not talking of option arguments as mandatory but rather the options themselves.
getopt_long()is not part of the C language. It is a GNU invention which is available in some C implementations, but far from all. The version ofgetopt_long()in glibc (used in most Linux distributions) does not allow you to specify that an option is mandatory. You'll have to check them explicitly after you're done parsing the command line.
I would like to port a program which is using urllib and json (Python 3) to C. My question is which libraries exist to replace urllib and json in C and which are the best (easier, documented, fast)? If there are not good libraries in C I also accept C++ Thank you all.
For JSON,json.orghas a list of implementations for a variety of languages, including C. Most of them should be fairly lightweight and fast. To replace urllib, you probably want to look atlibcURL.
``` int i; // A. extern int i; // B. ``` I know A is a variable's definition. Namely, the compiler creates an object and assigns a block of memory to the variablei. But what is B? What's the difference between the definition and the declaration?
It's a declaration. It says there is an integerithat will be defined elsewhere.
Consider that my system has memory, but it is scattered in different places (fragmented). There are no four contiguous memory locations that are free. In that scenario, if I declare a character array of size 10 in the C language, what will happen ?
If"my system has memory, but it is scattered in different places(fragmented)"means, thatheap virtual memoryis fragmented, and"declare a character array of size 10"means, that you create character array of size 10 instack memory: ``` char str[10]; ``` , then array will be successfully created. If"declare a character array of size 10"means, that you allocate memory with malloc() (allocate in heap): ``` char *str2; str2 = (char*) malloc(10 * sizeof(char)); ``` , then malloc() will return NULL.
I tried the code in my system. This is what I got...... 1) ``` #include <stdio.h> int main() { //int a = 10; printf("%s"); return 0; } Output: 1í^áäðPTRhh ``` 2) ``` #include <stdio.h> int main() { int a = 10; printf("%s\n"); return 0; } Output: __libc_start_main ``` I tried in another system( diff compiler). And the output was different. Actually it must be printing the topmost value in the stack. Then y isn't unique everywhere?
You're dealing withundefined behavior, so you can't expect it to be consistent, nor follow any kind of pattern across compilers, architectures or even runs of the same program.
I want to include an IP packet in Socket programming. I have a readymade Ip packet which contains igmp packet. I don't want to design igmp protocol but want to use that packet to sent igmp query. By some how the Ip packet I have must be recognize as IP packet and not as TCP/UDP data.
You have to usethe raw socketwithsendmsg. This needrootpermission.
What is a good way to create a three-state Boolean in a C-based language?
While others have offered answers, I'd like to offer a justification for the best one. Use integer values -1/0/1 (or really, any negative/zero/positive). With this scheme, there is an extremely efficient check for any subset of possible values: ``` (x<0) /* {-1} */ (!x) /* {0} */ (x>0) /* {1} */ (x<=0) /* {-1,0} */ (x) /* {-1,1} */ (x>=0) /* {0,1} */ ``` On x86, all of these will compile to a singletestopcode followed by a conditional jump opcode with the appropriate conditions. If you want to hide the implementation, you can use predicate macros for testing each of the 6 subsets.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed8 years ago.Improve this question What is a popular/good data structures and algorithm analysis book for C other than Data Structures, Algorithms, and Software Principles in C by Thomas Standish.
Algorithms in C(Sedgewick) is also good The Algorithm Design Manualis very readable
I'm trying to write a HTTP to ZeroMQ proxy with libevent (2.0.4) which should be able to handle very large (up to 4GB) file upload. The problem is I don't know how large post requests (larger than memory) are handled by libevent so if you have hints on how to implement large file uploading, please led me on the right path.
have you read the libevent source code? it's very readable. If you're using it's HTTP code, i think it uses the 'bufferedevent' (or is it evented buffers?) feature. You can simply set callbacks when the input buffer reaches the highwater mark.
I see "printf" instruction in sample codes of c language for microcontroller particularly in 8051. Since microcontrollers has no fixed output display what is the use of the "printf" instruction?
More likely than not, so you can attach a debugging console, either through an RS232 port, or as virtual output from an in-circuit emulator.
``` int main(int argc, char **argv) { char username[256]; username = ?; } ``` thanks~
You probably want to makeusernamebe a pointer, then you can just assign it: ``` int main(int argc, const char *const *argv) { const char *username; if (argc >= 2) username = argv[1]; else { fprintf(stderr, "usage: %s username ...\n", argv[0]); return 2; } /* ... */ } ``` But if you really want to copy the contents of the array, you are looking forstrncpy.
gcc 4.4.4 c89 I was just readinga discussion at DevXabout calling C++ code from C since I have to do something similar. I am just wondering what user Vijayan meant by "make sure that non POD types in C++ are opaque to C clients." Many thanks for any suggestions,
C can only deal with POD types. Consequently, you cannot pass objects of non-POD types to C programs (by value). Also, if you pass pointers of non-POD types to C programs, they can't interact with the objects pointed to.
This may sound like a strange question, but I am curious. If you want to make your code as efficient as possible, would this be something common for people to do? For example, you could use short datatypes instead of the int datatypes to do your processing. Or is it usually the case that the efficiency is much less than the time used to do efficient coding? Thanks...
You shouldneveruse the typesshort,char,float, or similar except for making arrays. Otherwise, useint,size_t,double, or larger types as-needed.
I have a little problem picking the right language to write my daemon, I am confused between C and C++, I want to use C++ because it is more expanded than C, but I want to use C because it is the starting point of everything in linux, I want to go for C++ as I have many resources about it, so, does it make any difference if I pick C++ instead of C? and what I will have good if I learn C more? I feel like if I go into C++ I will cover C within C++... Regards
Use whichever language you know best right now.
I would like to pack 2 floats into an long long. What would be the correct way to do this?
Slightly depends how portable you want it to be, in two senses: what platforms it works on at all, and what platforms it gives the same answer on. But something like this. ``` #include <stdint.h> long long pack(float lo, float hi) { assert(sizeof(float) == 4); assert(sizeof(long long) == 8); assert(CHAR_BIT == 8); uint32_t target; memcpy(&target, &lo, sizeof(target)); long long result = target; memcpy(&target, &hi, sizeof(target)); result += ((long long)target) << 32; return result; } ``` The "other" way to get the bits of a float as an integer in one write+read is with a so-called "union cast", but I prefer memcpy. You can also access the float oneunsigned charat a time and build up thelong longwith 8-bit shifts.
I have the following code ``` #include <stdio.h> #include <stdlib.h> char UPC[]="123456789ABC"; main() { int rc=0; printf("%016s\n",UPC); exit(rc); } ``` On AIX using the xlC compiler this code prints out with leading 0's ``` 0000123456789ABC ``` On Sles 11 it prints leading spaces using gcc version 4.3.2 [gcc-4_3-branch revision 141291] ``` 123456789ABC ``` Is there some format specifier I could use for strings to print out with leading 0's? I know that it works for numeric types.
``` printf("%.*d%s", (int)(w-strlen(s)), 0, s); ```
gcc 4.4.4 c89 Does any one know any sdp parses. That I can link to my application. Currently we are developing a SIP project. However, we need to parse the SDP for incoming/answering. However, we don't have much time to implement. So just wondering if there are some simple ones out there they are easy and quick to work with. Our application is written in c. Many thanks for any advice,
Check outFreeSDP. But it is distributed under GPL
Is it possible to store more than a byte value to a char type? Say for examplechar c;and I want to store 1000 inc. is it possible to do that?
Technically, no, you can't store more than a byte value to achartype. In C, acharand a byte are the same size, but not necessarily limited to 8 bits. Many standards bodies tend to use the term "octet" for an exactly-8-bit value. If you look insidelimits.h(from memory), you'll see theCHAR_BITsymbol (among others) telling you how many bits are actually used for acharand, if this is large enough then, yes, itcanstore the value 1000.
In some C project, I have seen this code: ``` static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { (void)ud; (void)osize; /* some code not using `ud` or `osize` */ return ptr; } ``` Do the two casts to void serve any purpose?
It is there to avoid warnings from the compiler because some parameters are unused.
suppose i have a variable int a=512 Now when i apply ~a which means one's complement in c.How i am getting -513 as the output. int is minimum 16 bits in size and binary equivalent of 512 is 0000 0010 0000 0000 And now when you do its one's complement it becomes 1111 1101 1111 1111. Now could someone tell me why the output is -513. Can I now Hope that guys in this forum understood my question.
Negative numbers are often represented astwo's complement, which is why it is interpreted the way it is. Assumingintis 16-bit, you will have the bitpattern1111 1101 1111 1111. Since the top-most bit is set, the number is negative. To convert to decimal, according to the rules for two's complement, the number is first bitwise-inverted. This brings back your 512. Then one is added, which gives 513. And since the number was negative, we get -513.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago. ``` int main() { signed int bit=512, mBit; { mBit = ~bit; bit = bit & ~bit ; printf("%d %d", bit, mBit); } return 0; } ``` a. 0, 0b. 0, 513c. 512, 0d. 0, -513 Guys I am not having the answer of this question and also not able to interpret the question.so could you please provide your answers with proper explanation.
The correct answer is d:http://ideone.com/frKOz bit is 0 becausebit & ~bitalways results in a zero (1000000000 & 0111111111).mbit is -513 because inverting 512 is -513. Edit: Why ismbit-513? See explanation of signed-integer-handling:http://www.rwc.uc.edu/koehler/comath/13.html
I am beginnner to programming. I wrote this little program to reverse a string. But if I try to reverse a string which is less than 5 characters long then it gives wrong output. I cant seem to find whats wrong. ``` #include<stdio.h> #include<string.h> int main() { char test[50]; char rtest[50]; int i, j=0; printf("Enter string : "); scanf("%s", test); int max = strlen(test) - 1; for ( i = max; i>=0; i--) { rtest[j] = test[i]; j++; } printf("Reversal is : %s\n", rtest); return 0; } ```
You are not terminating the reversed string with a 0. (all strings in C are 0-terminated) In this case, the printf will (likely, depending on the unitialized contents of the rtest array) create a buffer overflow. Add artest[max+1]=0;after the for loop and everything should be fine. Otherwise you can declarechar rtest[50] = {0}(this will initialize the whole array with 0s).
``` #include <stdio.h> #include <stdlib.h> void copyint(char *i,char** temp); int main() { char* a="00313"; char* temp; int inte; temp=(char*)malloc(sizeof(char)); copyint(a,&temp); inte=atoi(temp); printf("%s\n",temp); system("PAUSE"); free(temp); } void copyint(char *i,char** temp) { *temp=i; } ```
no question so point what is wrong on the first sight: - copyint copies single char into pointed memory. so what is being done: temp value is '0', random, random.... '0',random random is parsed by atoi - undefined since we don't know what under this pointer resides. and then it's printed out... usestrlen malloc strcpysequence instead Edit: it doesn't compile since you pass a (char*) into function which accepts (char). (copyint(a,&temp);)
How can I make sure not to happen like this? Is there any way to show exact place by numbers? ``` Name UID GID Dir Host root 0 0 /root paingpyi 500 500 /home/paingpyi 192.168.12.1 paingpyi 500 500 /home/paingpyi 192.168.12.1 ``` Code is ``` printf("Name \t\tUID \tGID \tDir \tHost\n"); printf("%s \t\t%d \t%d \t%s \t%s \n",up->ut_user,pw->pw_uid,pw->pw_gid,pw->pw_dir,up->ut_host); ```
Theprintfwidth specifiers are more appropriate for this kind of tasks than\t. You should have a look into the 'field width' section ofthe manual.