question
stringlengths
25
894
answer
stringlengths
4
863
This question already has answers here:Is there a standard function in C that would return the length of an array?(7 answers)Closed9 years ago. These 2 arrays are being modified a lot in the source code, that is why I want the preprocessor to count the number of members in the array. Is it also possible to have thegc...
There are a few things the preprocessor can do for you, but not quite what you describe. You can determine the number of elements in the array using a macro: ``` #define COUNTOF(arr) (sizeof(arr) / sizeof(*(arr))) ``` then somewhere in a function you can use assert() to test the values: ``` #include <assert.h> ......
I have a program similar to this: ``` switch(x) { case 1: for(i=0; i<10; i++) { if ((i==3) || (i==4) || (i==5) || (i==6) || (i==7)) { if (foobar[i]) break; // i am talking about this break } } ...further program break; /not this break ``` iffoobar[i]is true, would the program break out ...
Thebreakfollows a LIFO type nature, that is, the lastbreakwill come out of the first control structure. So, thebreakthat you chose would break out of the for-loop, not thecase.
I am trying to convert UTF-8 string to C/POSIX locale stringThe UTF-8 string is "abc123£" (in bash "abc123\302\243"`) iconv_open("", "UTF-8"); // "" means default program locale i.e. Ciconv_open("UCS-2LE", "UTF-8"); iconv() is returning EILSEQ to me in case 1, but success in case 2. What is the reason for this?Also...
Because yourClocale uses a character set (probably US-ASCII) that doesn't have a character for£, and the stringcan'tbe converted without loss.
I'm new in embedded systems development. I just want to compile some C code for this system: ``` uname -mrs Linux 2.6.32.28_stm24_0207 sh4 machine : STb7100 Reference board processor : 0 cpu family : sh4 cpu type : STx7100 cut : 3.x cpu flags : fpu cache type :...
A quickgoogle searchindicates that chip has an ST40 cpu core. Another google search turned upthis linkwhich has all of the instructions you need.
I am trying a create a crystal report for the monthly rate for twelve month showing in chart. For this task, I have adc_date(mm/dd/yyyy)as variable, which I changed in to ammyyyyformat. But when I see the group of month it starts always from01_XXXXwhich is not necessarily true. For example, for the report running th...
Have you tried to change the format to YYYYMM Hope this will help.
is it a correct way to convert anintvalue touint8_t: ``` int x = 3; uint8_t y = (uint8_t) x; ``` assume that x will never be less than 0. Althoughgccdoes not give any warning for the above lines, I just wanted to be sure if it is correct to do it or is there a better way to convert int to uint8_t? P.S. I use C on ...
It is correct but the cast is not necessary: ``` uint8_t y = (uint8_t) x; ``` is equivalent to ``` uint8_t y = x; ``` xis implicitely converted touint8_tbefore initialization in the declaration above.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed10 years ago.Improve this question I could not find any code samples using Google. Could someone please show me how to do it? I think we need...
You didn't search that much... recv function:http://msdn.microsoft.com/en-us/library/windows/desktop/ms740121(v=vs.85).aspx
Example ``` self.accessibilityTraits |= UIAccessibilityTraitAdjustable; ``` adds the UIAccessibilityTraitAdjustable option. But how to remove an option from the mask like this, without having to set everything?
Andit with the complement of the flag: ``` self.accessibilityTraits &= ~UIAccessibilityTraitAdjustable; ``` Ifself.accessibilityTraitswas: ``` 000110 ``` andUIAccessibilityTraitAdjustableis: ``` 000100 ``` (these values are examples; I haven't looked-up the real values) thenself.accessibilityTraits &= ~UIAccess...
``` #include<stdio.h> int main() { int x; x=~!printf; printf("%x",x); } ``` can some one explain me the process to derive the output of this program.
printfis a pointer to theprintffunction - thus it's ultimately an integer of some sort.!is unary NOT, meaning it returns0if the operand is true, and1is the operand is false. Sinceprintfis true (non-zero, because the function is defined), the subexpression so far is0.~is bitwise complement. It flips all the bits of the...
I am unable to give a proper reason for the following code's output. Can anybody help me. ``` int main() { int i; char ch; scanf("%c",&i); scanf("%d",&ch); printf("%d\n%c",i,ch); return 0; } ``` input output: ``` input: a 45 output: 0 - ```
You're reading anintinto achar. Assuming thatsizeof(int) != sizeof(char), this will result inscanfwriting beyond the end ofchwith undefined consequences. You should use the%iformat specifier forintarguments and the%cforchararguments ``` int main() { int i; char ch; scanf("%c",&ch); scanf("%d",&i); printf(...
I created my test function:void test(double** matrix); I want to pass to this function variable asdouble matrix[2][2] = {{1,2},{2,3}};. But my evil compiler writes:cannot convert «double (*)[2]» to «double**» for argument «1» to «void test(double**)». What do I need to do?
The types of the arguments and the parameters have to agree (or at least be compatible). Here, you have adouble[2][2], and you want to pass it to adouble**. The types are unrelated: an array of arrays is not an array of pointers (which would convert to a pointer to a pointer). If you really want to pass adouble [2]...
I am using the Linux ptrace API in a profiler I am writing. My pseudo C code looks like this: ``` setjmp(); measure(); alarm(N); while(1) { waitpid(child, &status, WNOHANG); if(child_process_exiting) { measure(); break; } } ``` The alarm signal handler is as follows: ``` void sig_handle...
Why not simple just sleep forNseconds, then do themeasurecall? If you install aSIGCHLDhandler to catch when the child process exits, then e.g.sleepwill be interrupted and return the number of seconds left. Something like ``` signal(SIGCHLD, sigchld_handler); do { measure(); } while (sleep(N) == 0); waitpid(......
Now I have some euc-jp encoded files that needed to be converted to utf-8 encoding. So I use the iconv command in bash: ``` iconv foo.c -f euc-jp -t utf-8 -o foo.c ``` But a problem occurs that it says: /usr/bin/iconv: illegal input sequence at position 30211 and file is truncated to a certain size (32 ~ 33KB). B...
Reading from and Writing to the same file with no syncronization? No, that is not a good idea. The file would be messed up. To do no harm to the data and generate no garbage, try this: ``` cp foo.c temp.input; iconv temp.input -f euc-jp -t utf-8 -o foo.c;rm temp.input; ```
Is this simply means whatever we do with object like cout gets in sync with stdout (and vice versa?). What does this exactly mean. Is stdio also sync with stdout?
If the synchronization is off, the C++ streams will be faster in some cases. By default, all standard C++ streams are synchronized with their respective C streams. Example: ``` #include <iostream> #include <cstdio> using namespace std; int main() { cout.sync_with_stdio(false); cout << "Hello\n"; printf(...
Basically I have a function which I would like to push a certain amount of stack space based on an integer variable. So I could make the function take up 3 bytes one time, then 5 or 6 another time. I need this to be on the stack not the heap, does anyone know how to do this via inserting assembly into my code or somet...
I believeallocais the function you are looking for.
I'm trying to build a statically linked copy of expect 5.45 from source. I have a statically linked copy of tcl 8.6.0 already built. I'm running configure as: ``` ./configure --with-tcl=$(tcl_root)/unix/ --with-tclinclude=$(tcl_root)/unix --disable-load --disable-shared ``` and then I runmake. The issue is it dum...
angry message about undefined references in ZLib Add-lzto the link?
As the question states I am looking to create a struct in C whose total size I do not know at compile time. For example, I would like to create a struct that contains a count value and an array with count elements. I know this could be implemented as: ``` typedef struct myStruct{ int count; int *myArray; } m...
It sounds like you're looking for flexible array members: ``` typedef struct myStruct { int count; int myArray[]; } myStruct; ``` Then, when you allocate it later: ``` myStruct *x = malloc(sizeof(myStruct) + n * sizeof(int)); x->count = n; ```
``` #include<stdio.h> int main() { int x; x=~!printf; printf("%x",x); } ``` can some one explain me the process to derive the output of this program.
printfis a pointer to theprintffunction - thus it's ultimately an integer of some sort.!is unary NOT, meaning it returns0if the operand is true, and1is the operand is false. Sinceprintfis true (non-zero, because the function is defined), the subexpression so far is0.~is bitwise complement. It flips all the bits of the...
I am unable to give a proper reason for the following code's output. Can anybody help me. ``` int main() { int i; char ch; scanf("%c",&i); scanf("%d",&ch); printf("%d\n%c",i,ch); return 0; } ``` input output: ``` input: a 45 output: 0 - ```
You're reading anintinto achar. Assuming thatsizeof(int) != sizeof(char), this will result inscanfwriting beyond the end ofchwith undefined consequences. You should use the%iformat specifier forintarguments and the%cforchararguments ``` int main() { int i; char ch; scanf("%c",&ch); scanf("%d",&i); printf(...
I created my test function:void test(double** matrix); I want to pass to this function variable asdouble matrix[2][2] = {{1,2},{2,3}};. But my evil compiler writes:cannot convert «double (*)[2]» to «double**» for argument «1» to «void test(double**)». What do I need to do?
The types of the arguments and the parameters have to agree (or at least be compatible). Here, you have adouble[2][2], and you want to pass it to adouble**. The types are unrelated: an array of arrays is not an array of pointers (which would convert to a pointer to a pointer). If you really want to pass adouble [2]...
I am using the Linux ptrace API in a profiler I am writing. My pseudo C code looks like this: ``` setjmp(); measure(); alarm(N); while(1) { waitpid(child, &status, WNOHANG); if(child_process_exiting) { measure(); break; } } ``` The alarm signal handler is as follows: ``` void sig_handle...
Why not simple just sleep forNseconds, then do themeasurecall? If you install aSIGCHLDhandler to catch when the child process exits, then e.g.sleepwill be interrupted and return the number of seconds left. Something like ``` signal(SIGCHLD, sigchld_handler); do { measure(); } while (sleep(N) == 0); waitpid(......
Hi everyone I got a trouble with the returning element of a function. I need to return a double pointer to pointer "double**". But I got a double[][] matrix. Here is the code: ``` double** createPalette(int r, int g, int b) { double incR = 1 / r, incG = 1 / g, incB = 1 / b; double Cp[r * g * b][3]; for (int i = 0; ...
I think you know the value ofr,g,b,so you can get the size of the matrix,you can do like this ``` void createPalette(int r, int g, int b, double matrix[][3]) ```
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 checklistClosed10...
Did you mean: ``` printf("%c\n", argv[2][1]); ``` argvis declaredchar* argv[], soargv[2][1]is of typechar, use%cinprintfto print. If you runprogram_name hello world, you will printowhich is the second character of the second argument.
a coredump file with corrupt stack, no any usefull info. How can i find the call stack? the stack shows : ``` #0 0x04229c7a in ?? () #1 0x00921fa7 in ?? () #2 0xbfc17e04 in ?? () ``` Backtrace stopped: previous frame inner to this frame (corrupt stack?) and the address of eip shows "cannot access memory"! thinks...
Displaying the call stack requires correct instruction pointer (eip), stack pointer (esp) and valid stack contents. From your output it looks like the stack had been corrupted and the previous function returned to some random address (eip=0x04229c7a). So, you are out of luck. Try running your program under valgrind...
I want to read double from text file e.g. 31 39.9316476397222 116.113516352222 I tried both, not work. I can only read the first few decimal digital e.g. 39.93164 but not 39.9316476397222 anyone knows why? Thanks! ``` int NodeID; double _lat,_long; fscanf (pFile, "%d %lf %lf", &NodeID,&_lat,&_long); printf ("I h...
According to thefscanf man page, you should use%lffor double : f, e, g (Floating point number) : A series of decimal digits, optionally containing a decimal point, optionally preceeded by a sign (+ or -) and optionally followed by the e or E character and a decimal integer (or some of the other sequences supported by...
I've a program to calculate the latency of an object in a pub-sub model. I've used the following function for timestamp: ``` uint64_t GetTimeStamp() { struct timeval tv; gettimeofday(&tv,NULL); return tv.tv_sec*(uint64_t)1000000+tv.tv_usec; } ``` The latency is measured as timestamp difference in publish...
Thetimevalstructure hastv_sec, which gives you the absolute value for the seconds, andtv_usec, which gives you theremainingfraction in micro seconds. So, you could get the resolution in micro seconds. For more information,http://www.gnu.org/software/libc/manual/html_node/Elapsed-Time.html
I have found out thattst_brkm()is not thread safe. But I don't how to check. What are the steps and tools to check that my function is thread safe or not?
Threads share the heap, but have their own private stack space. What this means is that each thread has its own view of local variables, but any data in the heap can be overwritten if you don't synchronize with mutexes/semaphores. So the first question to ask yourself is: What are the memory addresses I'm accessing an...
I wanted to ask if it is possible to allocate an array in C using malloc if we know the value of number of columns but not number of rows. ``` int Array[runtime value][N]; ```
Yes. A few ways to do that. Actually not a run-time, but you don't have to specify one dimension: ``` int array[][3] = {{1,2,3}, {4,5,6}}; ``` On stack, whererowsis run-time a variable: ``` int array[rows][COLUMNS]; ``` On heap usingmalloc, but don't forget to callfreelater: ``` int (*array)[COLUMNS]; array = ma...
``` #include <stdio.h> #include <stdlib.h> int main() { int randomnumber; randomnumber = rand() % 10; printf("%d\n", randomnumber); return 0; } ``` This is a simple program where randomnumber is an uninitialized int variable that is meant to be printed as a random number between 1 and 10. However, i...
You need a different seed at every execution. You can start to call at the beginning of your program: ``` srand(time(NULL)); ``` Note that% 10yields a result from0to9and not from1to10: just add1to your%expression to get1to10.
I'm trying to compile a program written in C../configurewas successful, but when I didmake, it gave me an error. I didmake check, and it said: ``` gcc -g -Wall -static -o multipht multipht.o multimatch.o multiweight.o multiwrite.o multisort.o multiclean.o /usr/bin/ld: cannot find -lc collect2: ld returned 1 exit ...
Your system appears to not have a statically linkable C library. That's actually pretty common these days. Take off the-staticflag and you should be good to go.
What is the advantage of using GDateTime instead of localtime_r in this code: ``` char time_str[100]; time_t t; struct tm lt; t = time(NULL); localtime_r(&t, &lt); strftime(time_str, 100, _("%Y%m%d-%H%M%S"), &lt); ```
GDateTime appears to be a component of the Gnome Library (GLib). As documented in GLib, GDateTime is a structure (and set of methods) for working with date/time data, capable of representing (with microsecond precision) any date/time from0001-01-01 00:00:00to9999-12-31 23:59:59.999999. Therefore,if(a) You're already ...
I'm trying to compile a library using-std=c++03, but compilation is failing becausenullptr_tis not defined. How can I guarantee C++03 instead of C++11 compilation using a hard-coded macro? Thanks in advance.
The only version detection present in the standard is the value of the macro__cplusplus:201103for C++11 (ISO/IEC 14882-2011 §16.8/1) and199711for C++98 (ISO/IEC 14882-1998 §16.8/1). C++03 didn't apparently deserve its own number and uses199711as well (ISO/IEC 14882-2003 §16.8/1). If this seems inadequate to you as a m...
I have some C code here: ``` char *cat_copy(char *dest, char *src) { char *start = dest; while (*++dest); //increment unless it can't anymore. while (*src++) { *dest = *(src - 1); dest++; } return start; } ``` I had to usewhile (*++dest)to get it to work, instead ofwhile ...
``` while (*++dest); ``` is like ``` do { dest++; // or ++dest } while (*dest); ``` where as ``` while (*dest++); ``` is like ``` while (*dest) { dest++; } dest++; ``` You need to copy all thechars including the NUL byte. Withwhile (*++dest);you are incrementingdestbefore dereferencing it. Had thefirstcha...
My CS course is taking a bit of a turn from Java to C. I'm busy going over pointers at the moment and I have come across that the ++ operator for incrementing doens't work when dereferencing. This is more just a curiosity question than anything else. Just not used to the pointers concept just yet. Am I just doing some...
When you want to increment the value you have to make sure you use parenthesis. ``` (*pointer)++; ```
This question already has answers here:Splitting an Array in C(2 answers)Closed9 years ago. Say I have a void* array 32 bytes long and I want to remove the data from byte 8 to byte 16. Is it possible to "cut out" these bytes somehow?
Since an array in C is a contiguous region of memory, you cannot "cut out" its parts without making a copy. Here is how to do it withmemcpy: ``` char copy[16]; char *ptr = voidPtr; memcpy(copy, ptr, 8); // Copy bytes 0..7 memcpy(copy+8, ptr+16, 8); // Copy bytes 16..31 ```
I wrote this incredibly stupid code ``` #include <stdio.h> main(){ int new[10], i; for(i=1; i<=10; ++i){ new[i] = 0; } for(i=1;i<=10; ++i) { printf("%d", new[i]); } } ``` I compiled this using GCC on Xubuntu and then did the ./a.out. The c...
C arrays are 0 indexed - your program writes outside the boundaries of thenewarray, so it causes undefined behaviour. In this case, you probably are overwriting theivariable, so you end up with an infinite loop. You need to change your loops: ``` for (i = 0; i < 10; i++) { new[i] = 0; } ``` and: ``` for (i = ...
I was wondering why the outcome of this program is 5621? ``` #include <stdio.h> main() { int i=56; printf("%d\n",printf("%d",printf("%d",i))); getch(); } ```
printfreturns the amount of characters it has printed. So first the most innerprintfgets called with 56, printing56. Then it returns the amount of characters it has printed (2) to the middleprintf, printing2. Then finally the amount of characters printed (1) gets passed into the outerprintf, which then gets printed t...
Is there any data type that is capable of storing values within range 0<X<10^20 in c/c++??
Sincelog2(10^20) = ~66.43you will need an integer made by128bits to store the number with integer precision. Actually, as pointed out by delnan in comment,67bits would be sufficient, by rounding to72bits with 8 bits alignment or96bits with 32 bits alignment. So, if you don't require an exact integer representation, y...
I need to initialize a variable and test its value. What is the most efficient way to do this? ``` char *key = get_key(item); if (key != NULL) { // do something } ``` OR ``` char *key; if (key = get_key(item)) { // do something } ``` Do side effects produce some advantage or not? Thanks!
Ah, good ol' "most efficient way"...No. NOPE. Forget efficiency. Even if there was a difference,this would very likely be premature optimization. But in this particular case, the only difference is in terminology (your second example is not, technically, initialization but an assignment expression), and your compiler...
I am writing to alsa in 10ms period to play music, it works great at beginning, however, it has some choppy sounds after 30min playing, and the choppy sounds only lasts for a few mins. Any ideas why? Environment is: Arm cortex-A8 audio codec TLV320AIC3106 linux kernel version: 3.2.0 os: ubuntu 12.04.2 LTS
Ok, I found the problem. On PC, we don't need to call snd_pcm_sw_params_set_avail_min, it works great. However, on our arm machine, we have to set it, otherwise, the status of the buffer is unpredictable, which caused choppy sound and background noise. And when you check the status of the playback device, u won't see...
When accessing an array we use the operator[]like so: ``` int a[5]; ... a[b] = 12; ``` What is the proper data type for the variablebabove? I've found thata[b]is equivalent to*(a + b), which makes me think that I would wantbto bevoid*orsize_tbut, I'm not sure.
From the C standard(ISO/IEC 9899:TC2) Sec6.5.2.1 Array subscripting A postfix expression followed by an expression in square brackets[]is a subscripted designation of an element of an array object. The definition of the subscript operator[]is thatE1[E2]is identical to(*((E1)+(E2))). Because of the conversion rules ...
Is it possible to force a compiler (gccorclangin my case) to use a certain register, lets sayR15onx86_64for a certain variable and also prohibit it from usingR15for any other purpose besides that variable.
gcc can do it. The already citedgcc docsanswers your question of how to force a variable into a certain register. To stop the compiler from generating code using this register for other purposes, use the gcc switch-ffixed-reg(see gcc doc for details).
for a given number ``` unsigned int a = 1203; ``` Increment the Most significant decimal digit only so for above sample ``` a = 2203; ``` How can this be achieved? i started like this ``` for (n=a; n; n/=10){ b = n%10;} ``` This gives msb then increment b++; But failed to put back the whole number? Is there a...
You were actually pretty close. ``` int x = 1; for (n=a; n; n/=10) { x *= 10; } a += x; ```
This question already has answers here:What will happen if '&' is not put in a 'scanf' statement?(6 answers)Closed5 years ago. Learning C, trying to code a program that outputs the sum of the cube and square of an inputted number. ``` #include <stdio.h> main() { int a; scanf("%d",a); printf("%d",cube(a)+sqr(a)); } ...
scanfneeds a pointer: ``` scanf("%d",&a); ``` instead of ``` scanf("%d",a); ```
Say I have a C / C++ application, and I wish to have it make requests via http, and receive responses, how might I choose to encrypt the data that is going / in or out? I can worry about decryption on either end later, for now I would like to get the encryption side of this.
Transport Layer Security (TLS 1.0, 1.1, 1.2) is a pretty standard protocol to use. You'll find quite a domain of open source libraries and OS-level APIs that support this protocol. This is, however, the issue. OS X, for instance, you'll have to leverage this through Transport Security; which is a completely different ...
I am running the below code but getting no output on console screen. Please Explain: ``` #include <stdio.h> void main() { enum days {sun,mon,tue,wed,thru,fri,sat}; } ```
``` #include <stdio.h> int main() { printf("sun, mon, tue, wed, thru, fri, sat\n"); return 0; } ``` Is that what you were trying to do?
I'm writing a program to read fromstdinand then writes what it reads tostdout, unescaping any escaped hex numbers it finds. All the numbers i want to read are 8 bit. This is what i have so far ``` while((c = fgetc(stdin)) != EOF) { if(c == '%') { fscanf(stdin,"%x",&r); printf("%i \n",r); } } `...
If you wantscanf(et al) to read only two characters, then tell it to do so: ``` scanf("%2x", &r); ``` See e.g.this referencefor information about thescanfformatting.
How to readsend(sock_fd, line, size, 0); I have a program like this, if (send(new_socket,sendToEMVSS,EMVSSSendBufferLength,0)!=EMVSSSendBufferLength) I try to run the program but the result is always!=EMVSSSendBufferLength
You really need to keep the return value. If it is -1, than you'll find detailed error information inerrno.If it is positive, but less thanEMVSSSendBufferLengthit means only that many bytes were send and you'll have to send the rest with separate call. That separate call will likely block (or fail witherrno == EAGAIN...
I have some C code here: ``` char *cat_copy(char *dest, char *src) { char *start = dest; while (*++dest); //increment unless it can't anymore. while (*src++) { *dest = *(src - 1); dest++; } return start; } ``` I had to usewhile (*++dest)to get it to work, instead ofwhile ...
``` while (*++dest); ``` is like ``` do { dest++; // or ++dest } while (*dest); ``` where as ``` while (*dest++); ``` is like ``` while (*dest) { dest++; } dest++; ``` You need to copy all thechars including the NUL byte. Withwhile (*++dest);you are incrementingdestbefore dereferencing it. Had thefirstcha...
My CS course is taking a bit of a turn from Java to C. I'm busy going over pointers at the moment and I have come across that the ++ operator for incrementing doens't work when dereferencing. This is more just a curiosity question than anything else. Just not used to the pointers concept just yet. Am I just doing some...
When you want to increment the value you have to make sure you use parenthesis. ``` (*pointer)++; ```
This question already has answers here:Splitting an Array in C(2 answers)Closed9 years ago. Say I have a void* array 32 bytes long and I want to remove the data from byte 8 to byte 16. Is it possible to "cut out" these bytes somehow?
Since an array in C is a contiguous region of memory, you cannot "cut out" its parts without making a copy. Here is how to do it withmemcpy: ``` char copy[16]; char *ptr = voidPtr; memcpy(copy, ptr, 8); // Copy bytes 0..7 memcpy(copy+8, ptr+16, 8); // Copy bytes 16..31 ```
I wrote this incredibly stupid code ``` #include <stdio.h> main(){ int new[10], i; for(i=1; i<=10; ++i){ new[i] = 0; } for(i=1;i<=10; ++i) { printf("%d", new[i]); } } ``` I compiled this using GCC on Xubuntu and then did the ./a.out. The c...
C arrays are 0 indexed - your program writes outside the boundaries of thenewarray, so it causes undefined behaviour. In this case, you probably are overwriting theivariable, so you end up with an infinite loop. You need to change your loops: ``` for (i = 0; i < 10; i++) { new[i] = 0; } ``` and: ``` for (i = ...
I was wondering why the outcome of this program is 5621? ``` #include <stdio.h> main() { int i=56; printf("%d\n",printf("%d",printf("%d",i))); getch(); } ```
printfreturns the amount of characters it has printed. So first the most innerprintfgets called with 56, printing56. Then it returns the amount of characters it has printed (2) to the middleprintf, printing2. Then finally the amount of characters printed (1) gets passed into the outerprintf, which then gets printed t...
Is there any data type that is capable of storing values within range 0<X<10^20 in c/c++??
Sincelog2(10^20) = ~66.43you will need an integer made by128bits to store the number with integer precision. Actually, as pointed out by delnan in comment,67bits would be sufficient, by rounding to72bits with 8 bits alignment or96bits with 32 bits alignment. So, if you don't require an exact integer representation, y...
I need to initialize a variable and test its value. What is the most efficient way to do this? ``` char *key = get_key(item); if (key != NULL) { // do something } ``` OR ``` char *key; if (key = get_key(item)) { // do something } ``` Do side effects produce some advantage or not? Thanks!
Ah, good ol' "most efficient way"...No. NOPE. Forget efficiency. Even if there was a difference,this would very likely be premature optimization. But in this particular case, the only difference is in terminology (your second example is not, technically, initialization but an assignment expression), and your compiler...
I am writing to alsa in 10ms period to play music, it works great at beginning, however, it has some choppy sounds after 30min playing, and the choppy sounds only lasts for a few mins. Any ideas why? Environment is: Arm cortex-A8 audio codec TLV320AIC3106 linux kernel version: 3.2.0 os: ubuntu 12.04.2 LTS
Ok, I found the problem. On PC, we don't need to call snd_pcm_sw_params_set_avail_min, it works great. However, on our arm machine, we have to set it, otherwise, the status of the buffer is unpredictable, which caused choppy sound and background noise. And when you check the status of the playback device, u won't see...
When accessing an array we use the operator[]like so: ``` int a[5]; ... a[b] = 12; ``` What is the proper data type for the variablebabove? I've found thata[b]is equivalent to*(a + b), which makes me think that I would wantbto bevoid*orsize_tbut, I'm not sure.
From the C standard(ISO/IEC 9899:TC2) Sec6.5.2.1 Array subscripting A postfix expression followed by an expression in square brackets[]is a subscripted designation of an element of an array object. The definition of the subscript operator[]is thatE1[E2]is identical to(*((E1)+(E2))). Because of the conversion rules ...
Is it possible to force a compiler (gccorclangin my case) to use a certain register, lets sayR15onx86_64for a certain variable and also prohibit it from usingR15for any other purpose besides that variable.
gcc can do it. The already citedgcc docsanswers your question of how to force a variable into a certain register. To stop the compiler from generating code using this register for other purposes, use the gcc switch-ffixed-reg(see gcc doc for details).
for a given number ``` unsigned int a = 1203; ``` Increment the Most significant decimal digit only so for above sample ``` a = 2203; ``` How can this be achieved? i started like this ``` for (n=a; n; n/=10){ b = n%10;} ``` This gives msb then increment b++; But failed to put back the whole number? Is there a...
You were actually pretty close. ``` int x = 1; for (n=a; n; n/=10) { x *= 10; } a += x; ```
This question already has answers here:What will happen if '&' is not put in a 'scanf' statement?(6 answers)Closed5 years ago. Learning C, trying to code a program that outputs the sum of the cube and square of an inputted number. ``` #include <stdio.h> main() { int a; scanf("%d",a); printf("%d",cube(a)+sqr(a)); } ...
scanfneeds a pointer: ``` scanf("%d",&a); ``` instead of ``` scanf("%d",a); ```
Say I have a C / C++ application, and I wish to have it make requests via http, and receive responses, how might I choose to encrypt the data that is going / in or out? I can worry about decryption on either end later, for now I would like to get the encryption side of this.
Transport Layer Security (TLS 1.0, 1.1, 1.2) is a pretty standard protocol to use. You'll find quite a domain of open source libraries and OS-level APIs that support this protocol. This is, however, the issue. OS X, for instance, you'll have to leverage this through Transport Security; which is a completely different ...
I am running the below code but getting no output on console screen. Please Explain: ``` #include <stdio.h> void main() { enum days {sun,mon,tue,wed,thru,fri,sat}; } ```
``` #include <stdio.h> int main() { printf("sun, mon, tue, wed, thru, fri, sat\n"); return 0; } ``` Is that what you were trying to do?
I'm writing a program to read fromstdinand then writes what it reads tostdout, unescaping any escaped hex numbers it finds. All the numbers i want to read are 8 bit. This is what i have so far ``` while((c = fgetc(stdin)) != EOF) { if(c == '%') { fscanf(stdin,"%x",&r); printf("%i \n",r); } } `...
If you wantscanf(et al) to read only two characters, then tell it to do so: ``` scanf("%2x", &r); ``` See e.g.this referencefor information about thescanfformatting.
How to readsend(sock_fd, line, size, 0); I have a program like this, if (send(new_socket,sendToEMVSS,EMVSSSendBufferLength,0)!=EMVSSSendBufferLength) I try to run the program but the result is always!=EMVSSSendBufferLength
You really need to keep the return value. If it is -1, than you'll find detailed error information inerrno.If it is positive, but less thanEMVSSSendBufferLengthit means only that many bytes were send and you'll have to send the rest with separate call. That separate call will likely block (or fail witherrno == EAGAIN...
I have 4 process sharing a common semaphore, all the process have the same priority. The critical region inside the lock, has the read/write operation including the fflush() call. In the logs, I observed that after giving off the semaphore from a particular process, there is a considerable amount of time taken by ot...
Context switch between processes held inside kernel. It's a job of kernel scheduler to do the context switching, so you can't do much here other than trying to speed up scheduler context switching path. Another alternative might be to try figure out the problem and to improve your app by reducing lock contention (perh...
in "C Modern approach 2nd'ed " Are some exercises i can't understand the meaning. The result is 1, how do you read it ? Thank you. ``` #include <stdio.h> int main(void) { int i, j, k; i = 5; j = 0; k = -5; printf("%d", i && j || k); return (0); } ```
``` i && j || k ``` is equivalent to ``` (5 && 0) || -5 ``` equivalent to ``` 0 || -5 ``` equivalent to1. Logical operators yield a value of0or1.
What is the best way to copy a 32bits array into 16bits arrays? I know that "memcpy" uses hardware instruction.But is there a standard function to copy arrays with "changing size" in each element? I use gcc for armv7 (cortex A8). ``` uint32_t tab32[500]; uint16_t tab16[500]; for(int i=0;i<500;i++) tab16[i]=tab3...
On ARM cortex A8 with Neon instruction set, the fastest methods use interleaved read/write instructions: ``` vld2.16 {d0,d1}, [r0]! vst1.16 {d0}, [r1]! ``` or saturating instructions to convert a vector of 32-bit integers to a vector of 16-bit integers. Both of these methods are available in c using gcc intrinsic. ...
Is there way in C on Linux to only write to a file if it already exists? In other words, the opposite ofopen(..., O_CREAT|O_EXCL). Note that I don't want the existence check decoupled from the actual opening of the file (like callingstat()beforehand) because that would be a race condition.
Check forENOENTwhile trying to open the file without theO_CREATflag. ENOENT O_CREAT is not set and the named file does not exist; or O_CREAT is set and either the path prefix does not exist or the path argument points to an empty string.
I am just wondering howtypedefis not throwing any compilation error when its used with undeclared structure. Below code is compiling without any warning and error. My doubt is how come atypedefwith undeclared structure is not throwing any error. Is it same in all platforms ``` #include <stdio.h> typedef struct undec...
``` typdef struct undeclared_struct_st UND_STRUCT_S; ``` is valid. It declaresstruct undeclared_struct_stas an incompele type and then declaresUND_STRUCT_Sas a typedef tostruct undeclared_struct_st. You cannot create objects of incomplete type but you can create pointers to objects of incomplete type.struct undeclare...
A company has asked me to deliver them a c/c++ library. They want to use it in an iphone app, which is objective c based. I would prefer to deliver a library as opposed to code. Could they wrap the c/c++ library into their iphone app without any need to see the source code? Thanks
You need to refer below links to create Static library : links shows step by step process http://www.lextech.com/2013/02/static-libraries-in-ios/http://jaym2503.blogspot.in/2013/01/how-to-make-universal-static-library.html
This question already has answers here:Uses of C comma operator [duplicate](20 answers)Closed9 years ago. I had this problem when I accidentally deleted the method name. The code went from ``` bool bRet = MethodName(pData, pOutFilename); ``` to ``` bool bRet = (pData, pOutFilename); ``` but still compiled? What d...
it is the"comma operator"which evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).
I just started learning C, and I learnt that the / sign is the division operator. I was experimenting, and was wondering why 5/7 printf the number 0. Here is my program: ``` #include<stdio.h> main() { int n; n = 5/7; printf("%d", n); } ``` Thank you!
This is because of integer division.5/7makes0.71.., and the integer part of this number is0, hence it prints0. To solve this problem usefloattype (or double type) variables as well as constants for example try: ``` float f = 5.0 / 7.0; ``` print variablefwith format string%f
I am just wondering howtypedefis not throwing any compilation error when its used with undeclared structure. Below code is compiling without any warning and error. My doubt is how come atypedefwith undeclared structure is not throwing any error. Is it same in all platforms ``` #include <stdio.h> typedef struct undec...
``` typdef struct undeclared_struct_st UND_STRUCT_S; ``` is valid. It declaresstruct undeclared_struct_stas an incompele type and then declaresUND_STRUCT_Sas a typedef tostruct undeclared_struct_st. You cannot create objects of incomplete type but you can create pointers to objects of incomplete type.struct undeclare...
A company has asked me to deliver them a c/c++ library. They want to use it in an iphone app, which is objective c based. I would prefer to deliver a library as opposed to code. Could they wrap the c/c++ library into their iphone app without any need to see the source code? Thanks
You need to refer below links to create Static library : links shows step by step process http://www.lextech.com/2013/02/static-libraries-in-ios/http://jaym2503.blogspot.in/2013/01/how-to-make-universal-static-library.html
This question already has answers here:Uses of C comma operator [duplicate](20 answers)Closed9 years ago. I had this problem when I accidentally deleted the method name. The code went from ``` bool bRet = MethodName(pData, pOutFilename); ``` to ``` bool bRet = (pData, pOutFilename); ``` but still compiled? What d...
it is the"comma operator"which evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).
I just started learning C, and I learnt that the / sign is the division operator. I was experimenting, and was wondering why 5/7 printf the number 0. Here is my program: ``` #include<stdio.h> main() { int n; n = 5/7; printf("%d", n); } ``` Thank you!
This is because of integer division.5/7makes0.71.., and the integer part of this number is0, hence it prints0. To solve this problem usefloattype (or double type) variables as well as constants for example try: ``` float f = 5.0 / 7.0; ``` print variablefwith format string%f
While reading "Linux kernel development" by Robert Love, I found at page 119: The interrupt handler is normally marked static because it is never called directly from another file. For example: ``` static irqreturn_t intr_handler(int irq, void *dev) ``` But why it is so? I doubt this function is going to be called...
According tothis, the way the function is used is by "registering" it with the kernel. That is, there's a function such asInstallIntHdlrwhich you call and pass a pointer to your handler. The kernel can then use that pointer to call the function itself. My guess, though I'm not sure about this, is thatstaticis used as...
I am trying to understand pointers and here is a program in K&R that I am trying to implement. The program is strcpy with code from KR. ``` /*strcpy: copy t to s; pointer version 3*/ void strcpy(char *s, char *t){ while(*s++ = *t++) ; } ``` So to implement this program, I add ``` #include<st...
``` char *s="abc", *t="ABC" ; ``` string literals are not modifiable, however, achararray can be modified, so change it to : ``` char s[] ="abc", *t="ABC" ; ```
I am not understanding for loop statement and expression following it. Please do help me understand. ``` #include<stdio.h> int main() { int x = 1; int y = 1; for( ; y ; printf("%d %d\n",x,y)) y = x++ <= 5; return 0; } ``` And the output I got ``` 2 1 3 1 4 1 5 1 6 1 7 0 ```
y = x++ <= 5;==>y = (x++ <= 5);==> first comparexwith5to check whetherxis small then or equals to5or not. Result of(x++ <= 5)is either1,0assigned toy, Asxbecomes >5,(x++ <= 5)becomes0soy = 0and conditionfalseand loop break,
I am coding a graphical program in C and my cartesian values are in between [-1,1], I am having trouble rounding off values so that I can use them for plotting and further calculations. I know how to round values greater than 1 with decimals but this I haven't done before. So how would I go about rounding values? For...
You don't (and can't, to any high degree of accuracy, due to how floating point values are stored) round floating point values, you can only output them to different degrees of precision. If you wanted all your float values rounded to 1 decimal place before using them in calculations, then do your calculations with in...
A function model contains entries of pairs<condition_on_args, return_value>. Thereturn_valueexpression may refer to input arguments, for example(f!4 (k!3 (:var 0))). Here(:var 0)refers to the 0th input argument of the function model, and it is of kind Z3_VAR_AST. I want to transformreturn_valueto some internal progr...
You have to use the following API: ``` /** \brief Return index of de-Brujin bound variable. \pre Z3_get_ast_kind(a) == Z3_VAR_AST def_API('Z3_get_index_value', UINT, (_in(CONTEXT), _in(AST))) */ unsigned Z3_API Z3_get_index_value(__in Z3_context c, __in Z3_ast a); ```
This question already has answers here:How to escape the % (percent) sign in C's printf(13 answers)Closed7 years ago. Why doesn't this program print the%sign? ``` #include <stdio.h> main() { printf("%"); getch(); } ```
Your problem is that you have to change: ``` printf("%"); ``` to ``` printf("%%"); ``` Or you could use ASCII code and write: ``` printf("%c", 37); ``` :)
``` #include<stdio.h> void main() { float a = 5, b = 2; int c; c = a % b; printf("%d", c); } ``` I am getting floating point error n this program-me..someone please explain this..
You can only use%operator with integer operands. Usefmodfunction (declared inmath.h) for floating point operands.
I am wondering why the signature ofMPI_Sendis as below: ``` int MPI_Send(void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm) ``` The first parameter is of typevoid *. Why is the first parameter of typevoid *rather thanconst void *. WillMPI_Sendmodify the source? I ask such kind of quest...
Will MPI_Send modify the source? No, it won't. My question is why the first parameter is of type void * rather than const void *. Bad design. The first versions of MPI were released after C has been standardized in 1989 andconstavailable as a standard. A proposal to add the missingconsttoMPI_Sendand other MPI fun...
I am having this problem writing a function that when the user input x,y (the coordinate or index of two dimensional array) it will return 0 if there is nothing or 1 otherwise.
In order to do so, first thing you need to do is initializ the array. You can do it this way: ``` int i,j; for (int i = 0; i<SizeX; i++) { for (int j = 0; j<SizeY; j++) { arr[i][j] = 0; } } ``` Now you can easly check it this way: ``` int check (int arr[SizeX][SizeY] , int i , int j) { // out-of...
``` void reverse(char *s,int j,int i) { printf("%d\t%d\n",i,j); if(i<j) { swap(s, i, j); reverse(s,--j,++i); } } ``` I read on Stack Overflow that using the postincrement operators in the function call can pose problems but does the use of the preincrement in function calls is al...
Increment operators cause undefined behavior if they modify the same variable in the same sequence point (statement). For example if you call a function like this:foo(++i, ++i)the C standard doesn't say in which order the increments should be performed, and you can't predict what will be passed to the function. This ...
Is there a way to typedef a 2 dimensional array in C? Something like: ``` typedef char[10][10] board; ``` This example doesn't compile. Is there any way to do it? Or any other solution?
Try this: ``` typedef char board[10][10]; ``` Then you can define new array as this: ``` board double_array = {"hello", "world"}; ``` It's the same with: ``` char double_array[10][10] = {"hello", "world"}; ```
Why do GTK+ and several other frameworks provideTRUEandFALSEmacros? Is there any advantage to usingTRUEandFALSEinstead of the built-in C valuestrueandfalse? You can see their implementation here:http://www.gtk.org/api/2.6/glib/glib-Standard-Macros.html#TRUE:CAPS
C99 hastrueandfalse, earlier versions do not. That is why you often seeTRUEandFALSE#defined. As you can readhere,trueandfalseare1and0respectively, same asTRUEandFALSE.
This question already has an answer here:What is the difference between a qualifier and a modifier in C?(1 answer)Closed10 years ago. Could some one explain what is the difference between qualifiers and specifiers in C?
Assuming you're talking about types, then this is simply a lookup in the C standard. C99 section 6.7.2: type-specifier:void char short int ... C99 section 6.7.3: type-qualifier:const restrict volatile I imagine that it's clear that these are distinct categories of things...
I have seen in many posts that "in most of the cases array names decay into pointers".Can I know in what cases/expressions the array name doesn't decay into a pointer to its first elements?
Sure. In C99 there are three fundamental cases, namely: when it's the argument of the&(address-of) operator.when it's the argument of thesizeofoperator.When it's a string literal of typechar [N + 1]or a wide string literal of typewchar_t [N + 1](Nis the length of the string) which is used to initialize an array, as ...
This question already has an answer here:Why can't I treat an array like a pointer in C?(1 answer)Closed9 years ago. In my system, an undefined pointer has a default value of 0x00000000. ``` void Demo() { char cData; char *pExamplePtr; char pExampleArray[4]; &cData <--- Address is 0x12345678 pEx...
The pointer pExamplePtr does indeed have a valid address. Maybe what you meant to say is that it is not pointing to anything and hence the 0x00000000 but that's not necessarily the case. Also in regards withpExampleArray[4], this is an array, not a pointer and it does indeed have a vaild address as is the case with y...
I'm using MPLAB to compile a program in C using the CCS compiler. I want to set an output port as high or low using defined ports. ``` #bit portOut1 = PORTC.0 ``` So, I want to set myportOut1high or low. I had used 3 ways to do it, but just one had worked. But I'm not satisfied with that. 1: (Doesn't work, why?) ...
``` #define portOut1 pin_c0 output_bit(portOut1, value) ```
Suppose I have the following constants: ``` const char EASY = 'E'; const char NORMAL = 'N'; const char HARD = 'H'; const char LUNATIC = 'L'; ``` I want LUNATIC to be greater than HARD, which is greater than NORMAL, which is greater than EASY. How do I define them as such where the following will work: ``` int main...
Use enumeration: ``` enum Difficulty { EASY, NORMAL, HARD, LUNATIC }; int main(){ char diff1 = LUNATIC; char diff2 = NORMAL; if (diff1 > diff2){ printf("Lunatic is harder than normal"); } return 0; } ```
#pragma onceis not standard, but is supported by compilers like gcc and VC++. It helps to avoid inclusion guards. But, internally, does the compiler add inclusion guards for#pragma once? If not, how does the compiler ensure that such a header is included only once?
I'm sure it works just likeinclude_oncein PHP - there is a table of "files that has been included". The compiler, in this case, looks in the list for the file it is about to include and if a file has already been included, don't include it again. If the compiler, while processign the file, sees a#pragma once, then add...
``` int main(int argc, char const *argv[]) { char str[100][100]; int n, i; scanf("%d", &n); for (i = 0; i < n; i++) gets(str[i]); for (i = 0; i < n; i++) printf("%s\n",str[i]); } ``` Why i'm unable to read the string properly? ``` raja@raja-Inspiron-N5110:~/myctry$ ./a.out 2 ...
change ``` scanf("%d",&n); ``` to ``` scanf("%d\n",&n); ``` if you press enter to input your number. this form gets rid of the '\n' in str[1] when scanf().
Suppose, I am declaring my CvMat* as shown below and then converting it to cv::Mat and then doing the conversion of types fromCV_8UC1toCV_32FC1. Then after the conversion, I want to revert it back to CVMat*. Can anbody tell me how can I do the conversion from cv::Mat to CvMat* ? ``` CvMat* r1 = cvLoadImageM(argv[2], ...
You can convert CV_8UC1 to CV_32FC1 with C API usingcvConvertScale((src), (dst), 1, 0 )command as follows ``` // source image CvMat* src = cvLoadImageM(argv[2], 0); // allocate destination image of type CV_32F CvMat* dst = cvCreateMat(src->height, src->width, CV_32FC1) // convert src image to dst image (type CV_3...
I just started coding in C, and ran someone else's Makefile with the default C compiler set to gcc. I am on Mac OSX 10.8 Mountain Lion and I believe I installed the compiler with "XCode Command Line Tools." After running "make" on command line, I get these annoying .dSYM files for each program. I read that these are d...
The-gflag to GCC will generate debug symbols. You may simply remove that flag fromCFLAGS.
This question already has answers here:What happens here? sizeof(short_int_variable + char_variable)(5 answers)Closed10 years ago. Given this code snippet: ``` #include <stdio.h> int main() { short i = 20; char c = 97; printf("%d, %d, %d\n", sizeof(i), sizeof(c), sizeof(c + i)); ...
c + iis an integer expression (integer promotion!), sosizeof()returnssizeof(int)
The below program is printing 123828749, 0.000000 but I expected 123828749, 123828749.0. From where it is getting 0.000000 ? ``` #include <stdio.h> void main() { double x = 123828749.66; int y = x; printf("%d\n", y); printf("%lf\n", y); } ``` Thanks
In the second call toprintfyou are passing anint, but the format string is%lfwhich expects a floating point value to be passed. This invokes undefined behaviour. If you want to treatyas a floating point value when you pass it toprintf, you'll need an explicit conversion: ``` printf("%lf\n", (double)y); ```
Which Data Structure should be used for a Library Management Project? There are 5 operations: Buy a bookBuy a new copy of a bookRent a bookReturn back a bookdelete a copy of a book I know Hash Tables and AVL-Trees at the moment. I started my project with AVL, but I am not sure if it's the right choice.
It depends on what you want to achieve(performance, extensibility, simplicity), the above operations can be implemented with simple data structure like array or linked list. I recommand using simple data structure to implement your application first. When performance become a problem, consider other data structures l...