question
stringlengths
25
894
answer
stringlengths
4
863
Here is my problem: x is 11, y is 6 and z is 1. what is the value of w? ``` w = x == y || x != y && z > x; ``` I dont understand how to decide whether I should evaluate the || or the && first.
&&has higher precedence than||. What else does one need to know? ``` x == y || x != y && z > x; ``` x != yevaluates totrue, andz>xevaluates tofalsesox != y && z > xevaluates tofalse. So we have: ``` x == y || false; ``` Now sincex==yisfalsewe get: ``` false || false; ``` However order of evaluation does not depe...
``` struct check{ unsigned short a; unsigned short b; }; static unsigned char v[5] = {1,2,3,4,5}; struct check *p = (struct check *)v; printf("%d",p->a); printf("\t%d",p->b); ``` The answer is513and1027. I am not able to get why it is happening. Can anybody help me on understanding the concept.
It's not a good idea to cast pointers like this. Probably,unsigned shortis 2 bytes on your machine, and after the cast,p->agets the value0x0201, which is decimal513, andp->bgets the value of0x0403, which is decimal1027. Note that the result will be different on a machine with different endianess. For example, on my ...
How can I create a PS (PostScript) file in C language? For example, I want create file myfile.ps anddrawto PostScript this code: ``` %! newpath 0 0 moveto 120 120 lineto 144 120 lineto 200 122 lineto 0 0 lineto stroke showpage ```
Normally postscript is just ascii text, so the standard text-output facilities will work just fine. ``` #include <stdio.h> int main(void) { FILE *outfile; outfile = fopen("myfile.ps", "w"); fprintf(outfile, "%%!\n" "%d %d moveto\n" "%d %d lineto\n" "%d %d lineto\n" ...
This question already has answers here:problems in floating point comparison [duplicate](2 answers)Floating point comparison [duplicate](5 answers)Closed9 years ago. i have following code which gives strange output ``` #include<stdio.h> void main() { float a, x; a=6.7; if(a==6.7) printf("1\n"); else printf("...
floathas less precision thandouble, which would be the default type used for floating point literals. Since6.7cannot be represented with a finite number of binary digits, the less precisefloatrepresentation does not equal thedoublerepresentation.
As the title suggests how do i print 17 in the hexadecimal format(0x11). I have triedprintf("%04x",number);but it prints the number as 0011(correct but not what i want).
Try this its clean and simple. Hexadecimal ->printf("%#x",17); Octal ->printf("%#o",17); More about#. Here's the linkhttp://www.cplusplus.com/reference/cstdio/printf/
Here is my problem: x is 11, y is 6 and z is 1. what is the value of w? ``` w = x == y || x != y && z > x; ``` I dont understand how to decide whether I should evaluate the || or the && first.
&&has higher precedence than||. What else does one need to know? ``` x == y || x != y && z > x; ``` x != yevaluates totrue, andz>xevaluates tofalsesox != y && z > xevaluates tofalse. So we have: ``` x == y || false; ``` Now sincex==yisfalsewe get: ``` false || false; ``` However order of evaluation does not depe...
``` struct check{ unsigned short a; unsigned short b; }; static unsigned char v[5] = {1,2,3,4,5}; struct check *p = (struct check *)v; printf("%d",p->a); printf("\t%d",p->b); ``` The answer is513and1027. I am not able to get why it is happening. Can anybody help me on understanding the concept.
It's not a good idea to cast pointers like this. Probably,unsigned shortis 2 bytes on your machine, and after the cast,p->agets the value0x0201, which is decimal513, andp->bgets the value of0x0403, which is decimal1027. Note that the result will be different on a machine with different endianess. For example, on my ...
How can I create a PS (PostScript) file in C language? For example, I want create file myfile.ps anddrawto PostScript this code: ``` %! newpath 0 0 moveto 120 120 lineto 144 120 lineto 200 122 lineto 0 0 lineto stroke showpage ```
Normally postscript is just ascii text, so the standard text-output facilities will work just fine. ``` #include <stdio.h> int main(void) { FILE *outfile; outfile = fopen("myfile.ps", "w"); fprintf(outfile, "%%!\n" "%d %d moveto\n" "%d %d lineto\n" "%d %d lineto\n" ...
This question already has answers here:problems in floating point comparison [duplicate](2 answers)Floating point comparison [duplicate](5 answers)Closed9 years ago. i have following code which gives strange output ``` #include<stdio.h> void main() { float a, x; a=6.7; if(a==6.7) printf("1\n"); else printf("...
floathas less precision thandouble, which would be the default type used for floating point literals. Since6.7cannot be represented with a finite number of binary digits, the less precisefloatrepresentation does not equal thedoublerepresentation.
I need to rotate a bmp given an angle in multiples of 90. Im trying to figure out how to accomplish this. Can somebody guide me in the right direction to approach this problem? The rotation angles, which are multiples of 90 could be positive as well as negative. It should also accept angle 0 thanks for your time in ...
better approach: ``` struct bitmap { int** array[3]; //RGB int N; int M; }; void f(struct bitmap source, struct bitmap dest) { for(int i=0;i<source.N;i++) { for(int j=0;j<source.M;j++) { dest.array[j][source.N-i-1]=source.array[i][j]; } } dest.N=array.M; dest.M=array.N; } ``` Here's ...
This is a combined math and Objective C question I`m stuck in writing the logic of the following: The user will enter a number, lets say 1000, then i want to subtract this number from 1013, get the difference which is 13. Now I have a number , lets say 50, I want to add 1 to this number for every difference of 7 be...
someNumber = difference + floor(difference / 7);
I've created a program to determine largest number, but my lecturer says it isn't perfect, can anybody make it perfect? ``` #include <stdio.h> int main () { double a,b=0,n, i; printf("limit of n input: "); scanf ("%lf",&n); for (i=1;i<=n;i++) { scanf("%lf",&a); if (a>b) b=a; ...
If by "not perfect" she meant "doesn't properly handle negative numbers or an empty set", then you'd want to Treat n<1 as a special case (why should 0 be the largest of an empty set?)Read the first number outside of the loop, so you're not making as assumption as to the smallest possible number
I am having a problem with storing unsigned ints in a character array in C. The code i have is ``` static unsigned char dataArray[8]; // values before are 2400 and 2100 // array layout: 0 0 0 0 0 0 0 0 U32 sysTime1 = 2400; U32 sysTime2 = 2100; dataArray[0] = sysTime1; dataArray[4] = sysTime2; // values after are...
``` union u { unsigned char dataArray[8]; U32 sysTime[2]; } u s; s.sysTime[0]=2400; s.sysTime[0]=1200; ```
Apologize for ambiguous title but I simply did not know how else to put it. Anyway, I want a piece of code to do the same thing this does in one line (in an if statement) ``` ret= fee(XYZ); if((fii(ret) && foh(ret)) !=0) { //do something } ``` like put all that into something like ``` if(_______FUM________) ...
You could use thecomma operator: ``` if(ret = fee(XYZ), (fii(ret) && foh(ret)) !=0) ``` But why?! (Also, the!=0appears to be redundant.)
This question already has answers here:ftell at a position past 2GB(4 answers)Closed9 years ago. According to the unix man pagesftelleither returns -1 to indicate an error. The function definition is: ``` long int ftell ( FILE * stream ); ``` Wherelong intis a 32 bit integer (you needlong longfor 64 bit) however(...
You could either checkerrnoor use the 64 bit version offtellcalledoff64_t ftello64(FILE *stream).
I have a binary number (e.g 111001001). I am trying to get last 5 digits (01001). How can i do this? i thought to store each digit to an arrray and then get the values with a for loop. But is there any better way?
You can get just the last 5 bits by masking: ``` x = x & 0x1f; ``` If you want toprocesseach of these bits then you can test them individually in a loop, e.g. ``` for (i = 0; i < 5; ++i) { if (x & (1 << i)) // if bit i is set { // do something for bit i = 1 } else { // do someth...
I have built a VS2010 console app. When I run this app on a machine without the necessary dlls a dialog box pops up with the message "The program can't start because MSVCR100.dll is missing from your computer". That's fair enough. The problem is that the program hangs until someone clicks OK. This program is a part ...
You can change your project to static link the CRT rather than dynamic link it (set the run-time library option toMulti-threadedrather thanMulti-threaded DLL).
So I just started learning struct type in C but I'm a bit confused. I have a pretty long program which I'm working on and I'm not sure tohow to insert a name and age into the next unused element in the arrray using a static variable (e.g. called nextinsert) inside the function to remember where the next unused element...
For your question "how to insert a name and age", use: ``` strcpy(people[nextfreeplace],name); people[nextfreeplace].age = age; ``` You may need to includestring.hforstrcpy.
This question already has an answer here:Assign to itself: optimization or extraneous?(1 answer)Closed9 years ago. A co-worker wrote a function like this (the comment was written by me): ``` static void foo(void *arg) { //arg is NOT global variable arg = arg; // call other function, but doesn't use arg ...
This is just one way of suppressing a compiler warning for an unused argument. Other common methods are: ``` (void)arg; ``` or ``` #pragma unused (arg) // not supported by all compilers ```
I have a code here that would probably just delay 10 seconds before proceeding , but I want to add a feature that the user could wait that delay or press any key to continue, I know it wouldn't be just likedelay(10000) || getch();any way to do it? ``` #include <stdio.h> #include <conio.h> #include <dos.h> void main(...
It's actually quite easy usingalarm: ``` printf("Press Any Key or Wait for 10 Seconds to Continue"); alarm(10); getch(); alarm(0); ``` You might need to set a handler onSIGALRMthough.
I readcat /proc/[pid]/mapsgives the informaion about its address space. So I want to write a program which will print its own address space. My program is this; ``` pid_t pid; int fd; char *buf; pid = getpid(); fd = open("/proc/????/maps", O_RDONLY); ``` I'm getting the PID, but it won't help me to open t...
All modern procfs systems implement"/proc/self/"for the running process. Just ``` fd = open("/proc/self/maps", O_RDONLY); ``` If you still wish to create the path string yourself then you have to usesprintf ``` char filename[128]; sprintf(filename, "/proc/%d/maps", getpid()); fd = open(filename, O_RDONLY); ```
I need to rotate a bmp given an angle in multiples of 90. Im trying to figure out how to accomplish this. Can somebody guide me in the right direction to approach this problem? The rotation angles, which are multiples of 90 could be positive as well as negative. It should also accept angle 0 thanks for your time in ...
better approach: ``` struct bitmap { int** array[3]; //RGB int N; int M; }; void f(struct bitmap source, struct bitmap dest) { for(int i=0;i<source.N;i++) { for(int j=0;j<source.M;j++) { dest.array[j][source.N-i-1]=source.array[i][j]; } } dest.N=array.M; dest.M=array.N; } ``` Here's ...
This is a combined math and Objective C question I`m stuck in writing the logic of the following: The user will enter a number, lets say 1000, then i want to subtract this number from 1013, get the difference which is 13. Now I have a number , lets say 50, I want to add 1 to this number for every difference of 7 be...
someNumber = difference + floor(difference / 7);
I've created a program to determine largest number, but my lecturer says it isn't perfect, can anybody make it perfect? ``` #include <stdio.h> int main () { double a,b=0,n, i; printf("limit of n input: "); scanf ("%lf",&n); for (i=1;i<=n;i++) { scanf("%lf",&a); if (a>b) b=a; ...
If by "not perfect" she meant "doesn't properly handle negative numbers or an empty set", then you'd want to Treat n<1 as a special case (why should 0 be the largest of an empty set?)Read the first number outside of the loop, so you're not making as assumption as to the smallest possible number
I am having a problem with storing unsigned ints in a character array in C. The code i have is ``` static unsigned char dataArray[8]; // values before are 2400 and 2100 // array layout: 0 0 0 0 0 0 0 0 U32 sysTime1 = 2400; U32 sysTime2 = 2100; dataArray[0] = sysTime1; dataArray[4] = sysTime2; // values after are...
``` union u { unsigned char dataArray[8]; U32 sysTime[2]; } u s; s.sysTime[0]=2400; s.sysTime[0]=1200; ```
Hi i am usingMQCBto register a callback function on my queue for reading new data. I have usedMQGMOoption ofMQGMO_SYNCPOINT. So callMQCMITat the end of the callback function too. Immediately i callMQCTLand start consumption of messages in the queue, by which my callback function gets called. My situation here is, i a...
Look for Options MQOP_SUSPEND and MQOP_RESUME in MQCTL (seehttp://pic.dhe.ibm.com/infocenter/wmqv7/v7r1/index.jsp?topic=%2Fcom.ibm.mq.doc%2Ffr41300_.htm) Regards
I would like to hide some complexity from some non-trivial code I'm writing. Here, I would like to hide one level of indirection from a struct pointer, to make it more readable. I'm not asking whether this is clean or a best practice or not, I know it isn't, but I also know what I like to achieve :) So, how kosher is...
IMHO, most C programmers would prefer a function-style macro, like: ``` #define getmark(m) ((m) && (m)->o ? (m)->o->marked : -1) ```
If I declare a 2d c-style array of int data[X][Y] I am assuming that the compiler will create this as a single array similar to int data[X*Y]but is this guaranteed? Let's say for simplicity we are using standard compilers on an x86 architecture. Now what about int data[X][Y][Z]? Does the compiler create this as ...
Yes, multi-dimensional arrays of any order in C are contiguous. They're just "arrays of arrays", so to speak. Plenty more at thecomp.lang.c FAQ, section 6, Arrays and Pointers.
This was asked in one of the interview I gave. I couldn't answer this properly. I want to find out how many bits are enabled based on a number. Suppose , if the number is 2 , I should return 3. if the number is 3 , I should return 7 ``` 8 4 2 1 1 1 8 4 2 1 1 1 1 ``` Is there any easy way of do...
Yes, there is: subtract 1 from the corresponding power of 2, like this: ``` int allBitsSet = (1U << n) - 1; ``` The expression(1U << n) - 1computes the value of2to the power ofn, which always has this form in binary: ``` 1000...00 ``` i.e. one followed bynzeros. When you subtract1from a number of that form, you "b...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Closed9 years ago.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Questions ...
This is because you are assigning 1 (ASCII value of a character) tox. Assign'1'tox. It will give output1. ``` char x = '1'; printf("%c\n",x); ```
``` gcc -c ./foo/name.c ./bar/name.c ``` This will output a single file ./name.o. I'm assuming one overwrites the other. How can I get gcc to place the object files in the same directory as the source files, in order to prevent object files from overwriting each other? EDIT: For anyone wondering how to fix this in...
Divide into 2 commands. ``` gcc -c -o ./foo/name.o ./foo/name.c gcc -c -o ./bar/name.o ./bar/name.c ```
I want to get several parameters in Lua from a C function. I tried to push several arguments on the lua stack: ``` static int myFunc(lua_State *state) { lua_pushnumber(state, 1); lua_pushnumber(state, 2); lua_pushnumber(state, 3); return 1; } ``` and call it in Lua like this: ``` local a,b,c = myF...
The return value of the C function is the number of values returned. Change it toreturn 3;and you're good to go. Here, have a reference fromProgramming in Lua: ``` static int l_sin (lua_State *L) { double d = lua_tonumber(L, 1); /* get argument */ lua_pushnumber(L, sin(d)); /* push result */ return 1; /* n...
Hi i am usingMQCBto register a callback function on my queue for reading new data. I have usedMQGMOoption ofMQGMO_SYNCPOINT. So callMQCMITat the end of the callback function too. Immediately i callMQCTLand start consumption of messages in the queue, by which my callback function gets called. My situation here is, i a...
Look for Options MQOP_SUSPEND and MQOP_RESUME in MQCTL (seehttp://pic.dhe.ibm.com/infocenter/wmqv7/v7r1/index.jsp?topic=%2Fcom.ibm.mq.doc%2Ffr41300_.htm) Regards
I would like to hide some complexity from some non-trivial code I'm writing. Here, I would like to hide one level of indirection from a struct pointer, to make it more readable. I'm not asking whether this is clean or a best practice or not, I know it isn't, but I also know what I like to achieve :) So, how kosher is...
IMHO, most C programmers would prefer a function-style macro, like: ``` #define getmark(m) ((m) && (m)->o ? (m)->o->marked : -1) ```
If I declare a 2d c-style array of int data[X][Y] I am assuming that the compiler will create this as a single array similar to int data[X*Y]but is this guaranteed? Let's say for simplicity we are using standard compilers on an x86 architecture. Now what about int data[X][Y][Z]? Does the compiler create this as ...
Yes, multi-dimensional arrays of any order in C are contiguous. They're just "arrays of arrays", so to speak. Plenty more at thecomp.lang.c FAQ, section 6, Arrays and Pointers.
This was asked in one of the interview I gave. I couldn't answer this properly. I want to find out how many bits are enabled based on a number. Suppose , if the number is 2 , I should return 3. if the number is 3 , I should return 7 ``` 8 4 2 1 1 1 8 4 2 1 1 1 1 ``` Is there any easy way of do...
Yes, there is: subtract 1 from the corresponding power of 2, like this: ``` int allBitsSet = (1U << n) - 1; ``` The expression(1U << n) - 1computes the value of2to the power ofn, which always has this form in binary: ``` 1000...00 ``` i.e. one followed bynzeros. When you subtract1from a number of that form, you "b...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Closed9 years ago.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Questions ...
This is because you are assigning 1 (ASCII value of a character) tox. Assign'1'tox. It will give output1. ``` char x = '1'; printf("%c\n",x); ```
``` gcc -c ./foo/name.c ./bar/name.c ``` This will output a single file ./name.o. I'm assuming one overwrites the other. How can I get gcc to place the object files in the same directory as the source files, in order to prevent object files from overwriting each other? EDIT: For anyone wondering how to fix this in...
Divide into 2 commands. ``` gcc -c -o ./foo/name.o ./foo/name.c gcc -c -o ./bar/name.o ./bar/name.c ```
I want to get several parameters in Lua from a C function. I tried to push several arguments on the lua stack: ``` static int myFunc(lua_State *state) { lua_pushnumber(state, 1); lua_pushnumber(state, 2); lua_pushnumber(state, 3); return 1; } ``` and call it in Lua like this: ``` local a,b,c = myF...
The return value of the C function is the number of values returned. Change it toreturn 3;and you're good to go. Here, have a reference fromProgramming in Lua: ``` static int l_sin (lua_State *L) { double d = lua_tonumber(L, 1); /* get argument */ lua_pushnumber(L, sin(d)); /* push result */ return 1; /* n...
I have a strange line in my stacktrace that I want to investigate further: ``` 12 libsystem_c.dylib 0x3aa272dc free + 168 ``` If I understand correctly, libsystem_c is C standard library. Is the version used in the iOS open-sourced? Where can I get that source?
To be more specific, I think it is hosted here:https://opensource.apple.com/source/Libc/
I am currently wondering if there is a way to replace the format specifier %u by nothing using sprintf My question is about the use of a ternary operator in sprintf which gonna replace %u by a value or by nothing. Here is an example of what I am trying to do : ``` int main (void) { char mytab[10]={'\0'}; uint...
I think you should put the ternary operator on the format-string, choosing to use either"%u", or"", depending on the value of i. ``` sprintf(mytab, i? "\"%u\"" : "\"\"", i); ```
I see everyone recommends just using openGL and some others but I don't wanna. I just want to know if graphic.h will only compile in turbo c and not with gcc, Thanks
You might getgraphics.hcompiled (as#included part of some sources), but the linking (coming after the compilation) will fail, as gcc's linker (ld) would not link the compilation's result against the library (graphics.lib) implementing whatgraphics.hprototyped.
How can I split aconst char *string in the fastest possible way. ``` char *inputStr="abcde"; char buff[500]; ``` I would like to have in buffer the following formatted string, format of which must be: ``` IN('a','ab','abc','abcd','abcde') ``` I'm learning C and new to the language. I have no clue where to start on...
I don't think you can do this particularly "fast", it seems like it's quite heavily limited since it needs to iterate over the source string many times. I'd do something like: ``` void permute(char *out, const char *in) { const size_t in_len = strlen(in); char *put; strcpy(out, "IN("); put = out + 3; for(...
in our company's latest project, we want to move a char arry to left half a byte, e.g. ``` char buf[] = {0x12, 0x34, 0x56, 0x78, 0x21} ``` we want to make the buf like ``` 0x23, 0x45, 0x67, 0x82, 0x10 ``` how do I make the process more efficient, can you make the time complexity less than O(N) if there are N bytes...
Without more context, I would go even as far as questioning the need for an actual array. If you have 4 bytes, that can easily be represented using auint32_t, and then you can perform anO(1)shift operation: ``` uint32_t x = 0x12345678; uint32_t offByHalf = x << 4; ``` This way, you would replace array access with bi...
I am new to MFC. I am trying to do simple mfc application and I'm getting confuse in some places. For example,SetWindowTexthave two api,SetWindowTextA,SetWindowTextWone api takeschar *and another one acceptswchar_t *. What is the use ofchar *andwchar_t *?
charis used for so called ANSI family of functions (typically function name ends withA), or more commonly known as using ASCII character set. wchar_tis used for new so called Unicode (or Wide) family of functions (typically function name ends withW), which use UTF-16 character set. It is very similar to UCS-2, but no...
I just started learning C about a week ago and Im having some issues using the arrow operator "->". I tried looking up examples online but nothing seemd to help. Here is the simple program. ``` struct foo { int x; }; main(){ struct foo t; struct foo* pt; t.x = 1; pt->x = 2; //here } ``` when ...
You need to initializeptto point to something! Right now it's just anullundefined pointer. Try: ``` pt = &t; ``` for example.
I just started trying to learn C and have a pretty basic question. The code listed below outputs an error from the mult function stating that there are 'conflicting types for mult' I can't see how there are any conflicting types. If I were to replace the data types of these values to ints however, I have no problems ...
You haven't declaredmultbefore you use it, so the compiler implicitly declares it for you asint mult(). Then the compiler finds your definition and it doesn't match. Try adding a prototype before yourmain(): ``` double mult(double, double); ``` Or just define it beforemain().
I'm trying to compare my output to my instructor's output and he gave us this set of commands to follow, but for the second to last command, it complains about having an extra operand in 'output.diff'. ``` $ gcc -ansi -Wall -Werror -lm -o myprint-badges print-badges32.o grove.c badges.c $./myprint-badges > my.out $....
You need to redirect the output (you missed the>): ``` diff my.out alex.out > output.diff ``` Instead of the above, you could have just piped it intomore: ``` diff my.out alex.out | more ```
I see the following instruction in gdb ``` jmp *0x804a09c(,%eax,4) ``` Just prior to exececution I types these commands: ``` (gdb)p/x *0x804a09c $40 = 0x8048e0e (gdb) p $eax $41 = 6 ``` So when I try to calculate the address I will jump to, I get: ``` (gdb) p/x *0x804a09c + 4*$eax 0x8048e26 ``` However, the ...
``` jmp *0x804a09c(,%eax,4) ``` means to jump to the address that is stored at the result of this calculation0x804a09c(,%eax,4), the*on the whole not on just0x804a09c. AT&T syntax can be misleading, Intel syntax is more clear here: ``` jmp DWORD PTR [eax*4+0x804a09c] ``` so it should be: ``` (gdb) p/x *(0x80...
I am making a game in C++, and I have a directory in a weird location (the installation directory) with screenshots from my game taken with thePrint Screenkey. What I want to do is to create a button that opens Windows Explorer with the location of the screenshots. I was thinking about using C'ssystemfunction withex...
The best way to do this is with theSHOpenFolderAndSelectItems()function. This lets you open the default folder manager (i.e. not hard-coded to Explorer, respecting the user's choice) and has the benefit of letting you automatically select the newly created screenshots.
I want to use OpenCV's Canny edge detector, such as is outlined inthis question. For example: ``` cv::Canny(image,contours,10,350); ``` However, I wish to not only get the final thresholded image out, but I also wish to get the detected edge angle at each pixel. Is this possible in OpenCV?
cannydoesn't give you this directly. However, you can calculate the angle from the Sobel transform, which is used internally incanny(). Pseudo code: ``` cv::Canny(image,contours,10,350); cv::Sobel(image, dx, CV_64F, 1, 0, 3, 1, 0, cv::BORDER_REPLICATE); cv::Sobel(image, dy, CV_64F, 0, 1, 3, 1, 0, cv::BORDER_...
my code looks like this: ``` if((strcmp(argv[1], "-a") == 0) && (argc == 3)) { /* my code */ } else if((strcmp(argv[1], "-b") == 0) && (argc == 3)) { /* my code */ } ... ``` And so on. Is this the only way to work around comparing args? I read someplace that it can be done using a loop, but I can't seem to f...
There is a C function for that:getopt()
According toman popen, "output popen() streams are fully bufered by default". But for the following code, i can still get all the information of myls -lcommand, without thefflush(p)command. Does that make sence? I thought I would need thefflush(p)to flush the command's output that are stored in the user buffer, to the...
That's an inputpopen()stream, not an output stream. Thefflush()function only operates on output or update streams, not input streams.
I have a c++ program and I want to display the line number of where the program crashes in the console ! I'm using VS2010! is that even possible? I use opencv , and opencv does it ! any idea?
I had a same issue, there was a code and I wasn't able to debug it (it had to run without stopping). I put below code before every suspecting line: ``` cout << __LINE__ << endl; ``` After that, when it crashed, I couldtrapthe problem. But a standard way is using a debugger and putconditionalbreakpoints. (I'm not ...
I have a the following class: ``` class CObj { private: MyOtherClass _member; }; ``` and the following code that creates an instance of CObj class: ``` CObj* obj = new Cobj; ``` obj is allocated on the heap, but: Are CObj::_member allocated on the heap too? or on the stack?
objis a pointer allocated "on the stack"; the objectobjpoints to is "on the heap", and, beingobj->_membera member (=a part) of such an object, it's on the heap too. In general, members, being part of the parent object, are allocated wherever their parent is stored.
I would like to know if, given the declarations below: ``` int first[1][COLUMN_NUMBER]; int second[COLUMN_NUMBER]; ``` the two bi-dimensional arrays could be accessed in the same or in a similar way. What I mean is: are they exchangeable? I am asking this because, due to an upgrade, I would like to avoid the refacto...
According tothis piece of code, there should be no difference. ``` #include <stdio.h> int main(void) { int const COLUMN_NUMBER = 10; union { int first[1][COLUMN_NUMBER]; int second[COLUMN_NUMBER]; } u; u.first[0][5] = 3; printf("%d\n", u.second[5]); return 0; } ```
following is extract from the book MISRA C:2012 which I am unable to understand The value of composite expression (+ ,- ,* ,/ ,&, |, ^, <<, >>, ?:) shall not be assigned to an object with wider type. Example: ``` u32a = u16a + u16b; //non - compliant to MISRA C guidelines ``` where u16 is uint16_t and u32 is u...
This is because you never know how your compiler will deal with (u16a + u16b) expression, since it may consider to store the result in 16-bits as well, before assigning it to target variable (consider 8 and 16 bit targets used in embedded systems). You expect (wrongly) that there is no overflow possible, while it is ...
``` char buffer[8]; memcpy(&buffer[0], "02000000", 8); //copy without '\0' ``` How can we interpret bytes in buffer as 0x00000002 and put it in the variable of type int?
You make it a string (with the terminating'\0') and usestrtolto convert it. Byte-swapping an integer is simple: ``` #define SWAP16(x) (((x) & 0xff00) >> 8) | (((x) & 0x00ff) << 8) #define SWAP32(x) (SWAP16(((x) & 0xffff0000) >> 16)) | (SWAP16((x) & 0x0000ffff) << 16) uint32_t value = SWAP32(strtol("02000000", N...
I have a c++ program and I want to display the line number of where the program crashes in the console ! I'm using VS2010! is that even possible? I use opencv , and opencv does it ! any idea?
I had a same issue, there was a code and I wasn't able to debug it (it had to run without stopping). I put below code before every suspecting line: ``` cout << __LINE__ << endl; ``` After that, when it crashed, I couldtrapthe problem. But a standard way is using a debugger and putconditionalbreakpoints. (I'm not ...
I have a the following class: ``` class CObj { private: MyOtherClass _member; }; ``` and the following code that creates an instance of CObj class: ``` CObj* obj = new Cobj; ``` obj is allocated on the heap, but: Are CObj::_member allocated on the heap too? or on the stack?
objis a pointer allocated "on the stack"; the objectobjpoints to is "on the heap", and, beingobj->_membera member (=a part) of such an object, it's on the heap too. In general, members, being part of the parent object, are allocated wherever their parent is stored.
I would like to know if, given the declarations below: ``` int first[1][COLUMN_NUMBER]; int second[COLUMN_NUMBER]; ``` the two bi-dimensional arrays could be accessed in the same or in a similar way. What I mean is: are they exchangeable? I am asking this because, due to an upgrade, I would like to avoid the refacto...
According tothis piece of code, there should be no difference. ``` #include <stdio.h> int main(void) { int const COLUMN_NUMBER = 10; union { int first[1][COLUMN_NUMBER]; int second[COLUMN_NUMBER]; } u; u.first[0][5] = 3; printf("%d\n", u.second[5]); return 0; } ```
following is extract from the book MISRA C:2012 which I am unable to understand The value of composite expression (+ ,- ,* ,/ ,&, |, ^, <<, >>, ?:) shall not be assigned to an object with wider type. Example: ``` u32a = u16a + u16b; //non - compliant to MISRA C guidelines ``` where u16 is uint16_t and u32 is u...
This is because you never know how your compiler will deal with (u16a + u16b) expression, since it may consider to store the result in 16-bits as well, before assigning it to target variable (consider 8 and 16 bit targets used in embedded systems). You expect (wrongly) that there is no overflow possible, while it is ...
``` char buffer[8]; memcpy(&buffer[0], "02000000", 8); //copy without '\0' ``` How can we interpret bytes in buffer as 0x00000002 and put it in the variable of type int?
You make it a string (with the terminating'\0') and usestrtolto convert it. Byte-swapping an integer is simple: ``` #define SWAP16(x) (((x) & 0xff00) >> 8) | (((x) & 0x00ff) << 8) #define SWAP32(x) (SWAP16(((x) & 0xffff0000) >> 16)) | (SWAP16((x) & 0x0000ffff) << 16) uint32_t value = SWAP32(strtol("02000000", N...
My C source code has many unintialized variables. The code is on RHEL 6.4 operating system. Is there a way to find all the uninitialized variables?
Findingallof them is impossible, in the mathematical sense (at least without false-positives). However, there are some tools to help find some of them: Turn on compiler warnings. Withgcc, this would be-Wuninitialized,-Winit-self, and-Wmaybe-uninitialized. Note that you will need to try this with various levels of opt...
I'm looking through the glib header files that reside in /usr/include to get a feel for what is going on behind the scenes. All the files I'm looking at simply declare a bunch of macros and functions but I want to take a look at the implementation of these functions.
The glibc source repository is here: https://sourceware.org/git/?p=glibc.git;a=tree Note thata lotof the interesting code is under thesysdepsdirectory, particularlysysdeps/unix/sysv/linux/*. Also worth noting is that stdio is split betweenstdio-commonandlibio, and all of the POSIX threads interfaces are implemented ...
Here is what I found in an open source project's code: ``` #if 0 static int print_cb(UNUSED void *ctx, void *i) { fprintf(stderr, "%i\n", *(int*)i); return 0; } #endif ``` Can you explain me what's the reason for this always false if? Thanks.
It's simply a way to use the preprocessor to comment out (prevent from compiling) a large block of code. It's pretty common. It's better than using the actual comment syntax since it doesn't nest. If you have: ``` int foo = 13; /* This won't be needed. */ ``` you can't comment it out by doing: ``` /* int foo = 13;...
I have Linux and I have a physical address: (i.e. 0x60000000).I want to read this address from user-space Linux program. This address might be in kernel space.
You need a kernel driver to export the phyisical address to user-level. Have a look at this driver:https://github.com/claudioscordino/mmap_alloc/blob/master/mmap_alloc.c
While Debugging Redis, I have compiled the code withmake noopt, and in Makefile, the optimize is set toO0. While debugging, I still got something optimized: In line 1, we can see all the parameters ofaeDeleteFileEvent, but when I step intoaeApiDelEvent(line -2), all its parameters are<optimized out>. Why these hap...
OK, thanks @alk(the fact is GCC optimized it) and @markys(V=1works for me). I find a tricky (maybe Bug, because it makes themake noopthas no effect on debugging) in Redis's Makefile, there was a rule that will include a.make-settings, and within the file, one of the option is setO2optimization. After comment the li...
My C source code has many unintialized variables. The code is on RHEL 6.4 operating system. Is there a way to find all the uninitialized variables?
Findingallof them is impossible, in the mathematical sense (at least without false-positives). However, there are some tools to help find some of them: Turn on compiler warnings. Withgcc, this would be-Wuninitialized,-Winit-self, and-Wmaybe-uninitialized. Note that you will need to try this with various levels of opt...
I'm looking through the glib header files that reside in /usr/include to get a feel for what is going on behind the scenes. All the files I'm looking at simply declare a bunch of macros and functions but I want to take a look at the implementation of these functions.
The glibc source repository is here: https://sourceware.org/git/?p=glibc.git;a=tree Note thata lotof the interesting code is under thesysdepsdirectory, particularlysysdeps/unix/sysv/linux/*. Also worth noting is that stdio is split betweenstdio-commonandlibio, and all of the POSIX threads interfaces are implemented ...
Here is what I found in an open source project's code: ``` #if 0 static int print_cb(UNUSED void *ctx, void *i) { fprintf(stderr, "%i\n", *(int*)i); return 0; } #endif ``` Can you explain me what's the reason for this always false if? Thanks.
It's simply a way to use the preprocessor to comment out (prevent from compiling) a large block of code. It's pretty common. It's better than using the actual comment syntax since it doesn't nest. If you have: ``` int foo = 13; /* This won't be needed. */ ``` you can't comment it out by doing: ``` /* int foo = 13;...
I have Linux and I have a physical address: (i.e. 0x60000000).I want to read this address from user-space Linux program. This address might be in kernel space.
You need a kernel driver to export the phyisical address to user-level. Have a look at this driver:https://github.com/claudioscordino/mmap_alloc/blob/master/mmap_alloc.c
While Debugging Redis, I have compiled the code withmake noopt, and in Makefile, the optimize is set toO0. While debugging, I still got something optimized: In line 1, we can see all the parameters ofaeDeleteFileEvent, but when I step intoaeApiDelEvent(line -2), all its parameters are<optimized out>. Why these hap...
OK, thanks @alk(the fact is GCC optimized it) and @markys(V=1works for me). I find a tricky (maybe Bug, because it makes themake noopthas no effect on debugging) in Redis's Makefile, there was a rule that will include a.make-settings, and within the file, one of the option is setO2optimization. After comment the li...
I have seen in SOhow to redirect STDIN, STDOUT, STDERR to /dev/null in C. This is done during startup of a daemon. But, why is this necessary for a proper startup of a unix/linux daemon? Bonus Question : What happens ifSTDOUTis closed and file descriptor is used without re-opening ?
stdin,stdoutandstderrare closed so that the daemon can detach successfully from the tty it was started from and also so that the daemon (or its child processes) won't write to the tty when its running. If you attempt to read/write from a closed file descriptor, the operation will fail anderrnowill be set toEBADF("fil...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ...
I have used this suite of data structures and been happy with the results: http://troydhanson.github.io/uthash/utlist.html The approach of using macros in a header file makes it quite lightweight and straightforward to incorporate into your projects
The Constraints portion of Section 6.3.2.2 of the ANSI C Standard includes the phrase: Each argument shall have a type such that its value may be assigned to an object with the unqualified version of the type of its corresponding parameter. Then, What the term 'unqualified version of type' means?
The C99 draft contains the following language, about the use of the word "qualified": Any type so far mentioned is an unqualified type. Each unqualified type has several qualified versions of its type, corresponding to the combinations of one, two, or all three of theconst,volatile, andrestrictqualifiers.The qual...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be abouta specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic onanother Stack Exchange site,...
Go toSettings>Style Configurator, and then toC/C++languages, and then to theTYPE WORDstyle. There you can add new typesuint8_t,uint16_t,uint32_t,int8_tetc in theUser-defined keywordstextbox.
I am trying to write a class that handles glsl and automatically gathers the number of: in(to vertex)/attributesuniformsout(from fragment) I know how to get the count of the first 2 using openGL's api but I cannot find a method for the third. If there is a way using openGL, I would prefer to use that. Otherwise I'll...
I think you wantglGetProgramInterfaceiv(). Something like this: ``` GLint numActiveOutputs = 0; glGetProgramInterfaceiv(prog, GL_PROGRAM_OUTPUT​, GL_ACTIVE_RESOURCES​, &numActiveOutputs ); ```
I am trying to write a class that handles glsl and automatically gathers the number of: in(to vertex)/attributesuniformsout(from fragment) I know how to get the count of the first 2 using openGL's api but I cannot find a method for the third. If there is a way using openGL, I would prefer to use that. Otherwise I'll...
I think you wantglGetProgramInterfaceiv(). Something like this: ``` GLint numActiveOutputs = 0; glGetProgramInterfaceiv(prog, GL_PROGRAM_OUTPUT​, GL_ACTIVE_RESOURCES​, &numActiveOutputs ); ```
I've done a little bit of reading on endianness and its role in C, but nothing has really managed to clarify this for me. I'm just starting out with C and I saw this example: ``` #include <stdio.h> int main(void) { int x = 017; int y = 12; int diff = x - y; printf("diff is %d\n", diff); return 0;...
Prefixing a number with0will tell the compiler to mark it as a number in octal (base 8) Just like prefixing it with0xwill tell it to use hex (base 16) For example: ``` int x = 05; // 5 in octal int y = 5; // 5 in decimal int z = 0x5; // 5 in hex ```
I am studying for a midterm and one of the questions is Which of the following statements will increment a value in the array, and leave the pointer address unchanged? Circle 0 or more. ``` int array[10]; int * ptr = array; ``` 1)*ptr++; 2)(*ptr)++; 3)*++ptr; 4)++*ptr; I have seen 1 and 2 used before and I belie...
http://en.cppreference.com/w/cpp/language/operator_precedencewill be helpful to you. Read through it and put the parenthesis in to the examples based on the precedence of the operators and everything will hopefully make some sense. The first would become*(ptr++)for instance.
I'm trying to get the size of a chunk of data sent via NetLink (Linux Kernel). I have tried withsize = nlh->nlmsg_len - NLMSG_HDRLEN, but that isn't returning the correct size. What's the correct way to get the message's data size?
Why would you believenlh->nlmsg_len - NLMSG_HDRLENis not returning the {message size without header} for the message you are looking at? If nlmsg_len contains, for example, the value 16 (that's what NLMSG_HDRLEN should be), then the payload of this message is empty. Your buffer may have more messages in it that want t...
I'm trying to make a simple program for my father to see on Father's Day. And I want All The characteres to appears right. I have full access to the computer where I want to execute the program and I can install anything on it. Here is my program: ``` #include <stdio.h> int main(void) { printf("Obrigado Dad, por ...
If you are using "Raster font" oncmd.exe, switch to a Unicode TrueType font (eg. "Lucida Console"), and as pointed by Andrejs, save your source file in UTF8.
This question already has an answer here:how to use the compiling time as automatic versioning-info?(1 answer)Closed9 years ago. So what I want is to have some preprocessor which gives the time of compilation. So that I can know which version of the program I'm running, by printing that time. Is it possible?
``` #include <stdio.h> int main(void) { printf("%s %s\n", __DATE__, __TIME__); return 0; } ``` Otherstandard predefined macros
I am working on a project using python but I was given example code in C and I just want to know what is the meaning ofFILEand the * in *fp. the actual example line of code that was given to me was: ``` int read_data(FILE *fp, int *id, double *prob_unm, double prob_mut) ```
In your line of code,fpmeans "file pointer". In the C standard library, for example when using thefopenfunction to open a file, aFILEpointer is returned.FILEis a kind of structure that holds information about the file. It is returned as a pointer because a reference to it is needed, as it will get changed by other low...
I'm trying to pass in an array of integers into my program. Is there a better way to convert it to integers? I'm currently getting an error: "Variable sized object may not be initialized" ``` for(i = 0; i < argc; i++) { int arr[i] = atoi(argv[i]); } ```
Assumingargcandargvare the arguments passed to main, it is unlikely thatargv[0]is something that you want to convert into an integer.argv[0]usually contains the name of the program. Your code snippet is declaring an array local to the loop body. What you likely want is an array defined outside the loop body, and you ...
I'm having trouble what this line of code does: ``` struct node* node = (struct node*) ``` Code is used in this context: ``` typedef struct node node; struct node* newNode(int key) { struct node* node = (struct node*) malloc(sizeof(struct node)); node->key = key; node->left = NULL; node->ri...
So, it's tricky ``` struct node* node = (struct node*) malloc(sizeof(struct node)); ``` can be rewrited as ``` struct node* node = (struct node*) malloc(sizeof(struct node)); ``` And it is just a type conversion. However, in C there is no necessary for explicit cast fromvoid*(return type ofmalloc) and vice-versa ...
I can't seem to find any documentation for LPTHREAD_START_ROUTINE for the C language. I found this but it is for .NET Framework 4.5 and it is deprecated:http://msdn.microsoft.com/en-us/library/aa964928.aspx The reason why I want to know is because I need it for CreateThread:http://msdn.microsoft.com/en-us/library/wi...
LPTHREAD_START_ROUTINEis actually documented under the name ofThreadProc: An application-defined function that serves as the starting address for a thread. Specify this address when calling theCreateThread,CreateRemoteThread, orCreateRemoteThreadExfunction.TheLPTHREAD_START_ROUTINEtype defines a pointer to this callb...
If I have a C program that I compile successfully and generate an executable, how do I instruct the program to open a new terminal window when I run it from the command line in a pre-existing terminal command prompt? I assume I use thesystem()function but what header is that in and what is the actual command arg it ta...
The header file isstdlib.hand the function signature isint system(const char *command). So in your case you could call the function like this to spawn a new terminal window: ``` #include <stdlib.h> int main(void) { int exit_status = system("gnome-terminal"); } ``` In C it's common to check the return value of m...
I am trying to compile a program to put on a BeagleBone black, but im getting this error when running the program on my board: ``` /lib/libc.so.6: version `GLIBC_2.17' not found ``` I made sure that i cross compiled for ARM (arm-linux-gnueabi-gcc). On my desktop, I have EGLIBC 2.17-9. What did i do wrong?
Had face the same problem. Solved it by the following steps. Downloaded "libc6_2.17-0ubuntu5.1_i386.deb"sudo dpkg -i ipts libc6_2.17-0ubuntu5.1_i386.deb sudo dpkg -i ipts libc6_2.17-0ubuntu5.1_i386.deb
I am learning now c and i am studying pointers. I have read some examples and I come up with this: ``` #include <stdio.h> int main () { float balance[10][5]; float *p; p = (float *) balance; *(p + 16) = 200.0; //init the balance[3][1] with the value 200.0 printf("%f\n", balanc...
Why i have to cast the balance with a (float *) ? This is becausepis of typefloat *whilebalanceis of typefloat (*)[5]after decaying to the pointer. is this because the array is 2 dimensions? Yes. so the pointer is also 2 dimensions? balancedecays tofloat (*)[5]. so i have to transform it to a 1 dimension ? Yes....
I'm trying to check if the line read from stdin begins with "login:" but strcmp does not seem to work. ``` char s1[20], s2[20]; fgets(s1, 20, stdin); strncpy(s2,s1,6); strcmp(s2, "login:"); if( strcmp(s2, "login:") == 0) printf("s2 = \"login:\"\n"); else printf("s2 != \"login:\"\n"); ``` I don't care what co...
strcmpreturns 0 if the two strings are exactly the same to accomplish what you want to do Use : strstr(s2 , "login:") (It returnNULLif the string doesn't exist ins2) or strncmp(s2 , "login:" , 6) This will compare the first 6 characters (ifs2begins with "login:" , it will return 0)
Fact 1: Due to some client-constraints we are unable to use Exception mechanism. Fact 2: Closing a handle which was already closed raises an Exception. Without going through the reasons for the mention facts, will callingGetHandleInformation()to detect whether or not the handle is still valid, and onlyif it iscallin...
You must not access a closed handle in any way, as it may refer to a different handle due to handle recycling. handle recycling means that any invalid handle can suddenly become valid again (but refer to an unrelated object). Raymond Chen - The Old New Thing.
This isn't a straight up coding question, there's no specific code involved. It's more of a general question that I've been struggling with to understand. What is the difference between an if statement, and an if statement for validity check/variable guard check? I ask this because my instructor told us to write a f...
There is no difference, there is only one kind ofifstatement. The condition is on the structure of your program, not on the specific "type" ofifstatement. The instructor is requiring that you don't introduce unnecessaryifstatements, except to check a "guard" variable, so presumably there is a process where by you can ...
I am trying to create a file, but it is opening in locked mode. How to make it in read write execute mode? ``` switch(choice){ case 1: printf("\n Enter the file: "); scanf("%s", file); open(file, O_CREAT, S_IRWXG); break; ```
The third argument of open doesn't actually have to be one of the defined flags. If you want it in +rwe mode for all users, just change your code to ``` open(file, O_CREAT, 0777); ``` EDIT: If you'd prefer to use the flags. Just combine them with the | command. You'll end up actually passing the same value in, bu...
I'm trying to make a simple program for my father to see on Father's Day. And I want All The characteres to appears right. I have full access to the computer where I want to execute the program and I can install anything on it. Here is my program: ``` #include <stdio.h> int main(void) { printf("Obrigado Dad, por ...
If you are using "Raster font" oncmd.exe, switch to a Unicode TrueType font (eg. "Lucida Console"), and as pointed by Andrejs, save your source file in UTF8.
This question already has an answer here:how to use the compiling time as automatic versioning-info?(1 answer)Closed9 years ago. So what I want is to have some preprocessor which gives the time of compilation. So that I can know which version of the program I'm running, by printing that time. Is it possible?
``` #include <stdio.h> int main(void) { printf("%s %s\n", __DATE__, __TIME__); return 0; } ``` Otherstandard predefined macros
I am working on a project using python but I was given example code in C and I just want to know what is the meaning ofFILEand the * in *fp. the actual example line of code that was given to me was: ``` int read_data(FILE *fp, int *id, double *prob_unm, double prob_mut) ```
In your line of code,fpmeans "file pointer". In the C standard library, for example when using thefopenfunction to open a file, aFILEpointer is returned.FILEis a kind of structure that holds information about the file. It is returned as a pointer because a reference to it is needed, as it will get changed by other low...
In C/C++ when I want to find sum of two chars - I get result in int.For example: ``` #include <stdio.h> int main(){ char a = 'a', b = 'b'; printf("%d + %d = %d\n", sizeof(a), sizeof(b), sizeof(a + b)); return 0; } ``` Prints ``` 1 + 1 = 4 ``` Why?
Because althoughaandbare each of typechar, the expressiona + bis of typeint. Anytime you do math with char types, they are converted to int before doing the actual calculations.
How do use vector or in-built sort function in C++ with most of the language in C? I am trying to just sort an array for a C program. Can it explained with a simple code with sort implementation? I am very new to C++.
If you want to sort inCthen you should useqsort. If you want to sort inC++then you should usestd::sort