question
stringlengths
25
894
answer
stringlengths
4
863
When we pass an array as an argument we accept it as a pointer, that is: ``` func(array);//In main I invoke the function array of type int and size 5 void func(int *arr) or void fun(int arr[])//As we know arr[] gets converted int *arr ``` Here the base address gets stored inarr. But when the passed array is acce...
Does the memory gets allocated for arr[5]? No, it doesn't. If no,why memory is not allocated? Because it's not necessary. The array, when passed to a function,alwaysdecays into a pointer. So, while arrays are not pointers and pointers are not arrays, in function arguments, the following pieces of code are equivalen...
I have to write a program in C (on a Unix-like system) and this is my problem: I have a file (FILE1) and I want to create another file (FILE2) which has the same permissions of FILE1. Then I have to create another file (FILE3) which has the same permissions of FILE1 but only for the owner. I would use chmod() to cha...
Thestat()andfstat()functions retrieve astruct stat, which includes a memberst_modeindicating the file mode, where the permissions are stored. You can pass this value tochmod()orfchmod()after masking out the non-file-permission bits: ``` struct stat st; if (stat(file1, &st)) { perror("stat"); } else { if (c...
In the new language standard C++11 is present the keywordconstexpr. Is there aconstexprin new standard C11 (not C++11) or planned in the future?
No, there is not aconstexpror similar usage keyword in C11. As to if it is planned in the future, the answer is "I don't know". C11 §6.6Constant expressionsgives the constrains on constant expression: Constant expressions shall not contain assignment, increment, decrement, function-call, or comma operators, except...
I have more than 3 million file descriptors on a Linux machine, so I look how socket buffers size against RAM size would constrain the maximum number of simultaneous tcp connections that the machine can handle. If you had similar experience, please, advise. Thank you.
It's not about RAM size, but rather about virtual memory size. Clearly you cannot have buffers exceeding the total virtual memory available on the computer. That said, if you are finding that things start to break when you have three million sockets open, you may be better off focusing your efforts on reducing the n...
I have a limited amount of variables to use so I would like to solve the following problem only using one variable. Is it possible? ``` char str[100]; // Type three words: printf("Type three words: "); scanf("%s %s %s",str,str,str); printf("You typed in the following words: \"%s\", \"%s\" and \"%s\"\n",str,st...
Use a loop? ``` char buf[0x100]; for (int i = 0; i < 3; i++) { scanf("%s", buf); printf("%s ", buf); } ``` Sidenote: but why not read the entire line at once, then parse it later using e. g.strtok_r()? ``` fgets(buf, sizeof buf, stdin); ``` is the way to go...
This question already has answers here:What are the applications of the ## preprocessor operator and gotchas to consider?(13 answers)The ## operator in C(7 answers)Closed10 years ago. What's the meaning of "##" in the following? ``` #define CC_SYNTHESIZE(varType, varName, funName)\ protected: varType varName;\ publi...
The operator ## concatenates two arguments leaving no blank spaces between them: e.g. ``` #define glue(a,b) a ## b glue(c,out) << "test"; ``` This would also be translated into: ``` cout << "test"; ```
This question already has answers here:Declaring a C function to return an array(5 answers)Closed10 years ago. How can one have a function returning a pointer to an array and what are the general things that one needs to keep in mind while doing that?
``` int (*foo(void))[4]; ``` declaresfooas a function with no parameters that returns a pointer to an array 4 ofint. For example: ``` int (*p)[4]; p = foo(); ```
I saw in many examples it is written that: ``` #define N 5 .... int a[N], *p; .... for (p = &a[0]; p < &a[N]; p++); ``` It is clear thata[N]doesn't exist, then why compiler is not giving any warning (like out of bound) or error or does it invoke UB?
The memory at&a[N]is never accessed by your program, so it's fine. The C standard allows comparison of pointers within or one past the end of an array object. Edit regarding discussion below: &a[N]doesnotcause undefined behaviour - it is exactly equivalent toa + N. From the C standard,6.5.3.2 Address and indirecti...
Why doesn't the following line of code produce an error? ``` double x = 4.2, y; ``` Also, x seems to be assigned to 4.2, and not the value of y (which seems to be 1e-39, or very close to 0).
It does the same as: ``` double x = 4.2; double y; ``` The "y" variable contains some junk value (since its value is unspecified) until you give it a value. It acts this way because the comma operator has lower precedence than assignment in C/C++.
I am trying to make data structure for a 64 bit integer in a 32 bit architecture.Any idea to do this will be appreciate . ``` struct make { int a;// how to make 64 bit integer in a 32 bit architecture. } ``` NOTE : I have a question, Will a C program compiled on a 32 bit Intel proces...
Use along long On the IA32 architecture, 64-bit integer (long long) are implemented in using two 32-bit registers (eax and edx).
I have a .cxx file and cmake file to help compile. However, when I run the code on the linux terminal, the correct files are outputted, as well as some (null) files (i.e. (null).5252 ) . I am trying to usesystem("sudo rm -- \(null\)*");in the .cxx code to delete the (null) files, but it doesn't seem to be working. It ...
In the string you are passing tosystem(), the parenthesis are being interpreted literally because of the backslash. This isn't really what you want. You want to pass the backslash along in the string, so you need to escape the backslashes themselves. ``` system("sudo rm -- \\(null\\)*"); ``` Or you can quote the fil...
I am using a memory monitoring library based on "WIN32 tool help functions". In its source code there are calls toCreateToolhelp32Snapshot(),Heap32ListFirst(),Heap32ListNext(), andCloseToolhelp32Snapshot(). My problem is that there is no prototype for CloseToolhelp32Snapshot() in the associated windows header file. ...
The documentation forCreateToolhelp32Snapshotsays: To destroy the snapshot, use theCloseHandlefunction. CloseToolhelp32Snapshotwould appear to be for WinCE/Mobile only.
Assign a memory location with address0x67ABand value0x1234using pointers. i am trying to assign a fixed location in memory using pointers and not usingmalloc()
The following code writes0x1234to the address0x67ABin the address space of the executing process, provided your C implementation supports this behavior (as it goes beyond what the C standard requires). You may need to use a type other thanuint16_t, depending on your precise needs. If you do not know what you are doing...
I have many different functions, and they all have simpleprintfstatements using__func__similar to this one: printf("%s - hello world!", __func__); Now the problem I am running into is that in some functions it returns<unknown>instead of the function name. Why is that? Am I doing something wrong? AFAIK__func__is a p...
It sounds like a header you are including must be doing something similar to thisbugand defining__func__as follows: ``` define __func__ "<unknown>" ``` and so you only see it when you include that header(s). A quick way to test for this would be to use__FUNCTION__in a section of the code where__func__does not work. ...
I want to store my data array in flash, so I am doingconst table[TABLE_SIZE] = {};. When working with AVR, I remember I used thePROGMEMattribute. Does usingconstdo the same asPROGMEMor is there a way to usePROGMEMin my M0?
Usestatic const. That's not precisely what it means, but most embedded compilers will interpret that as a sign that they should leave the table in ROM (and not add a copy to RAM). Note that you'll need to actually initialize it in the static initializer: you can't use{}and initialize it at runtime.
How should I call this in c programming: ``` char *fileNames[3] = {"string1", "string2", "string3"}; ``` Pointer array, array pointing to strings, or what? Not really laziness to look for the answer somewhere else, it is that I didn't find it. Update 1: I've called the above (whatever it is) fileNames because I'm ...
You generally can readsimpleC / C++ declarations from right-to-left, but you're supposed to follow theClockwise/Spiral Rule. It's an array of pointers to characters.
I'm sorry if this may seem like a silly question... I've a doubt about cvLoadImage in OpenCV: ``` IplImage *frame; for (unsigned int i = 0; i < LENGTH; i++) { frame = cvLoadImage(filename.c_str()); // do something... } ``` For each call ofcvLoadImageis a newIplImagestored in memory? Is the old variable poi...
Yes, memory allocated by cvLoadImage. Error appears because you not initialized frame in the beginning. It must be initialized by zero, or NULL.
I am trying to assign a 2D array of strings in the following way: ``` char *text_data[10][4]; //10 rows, 4 columns //All rows need to be same for (i = 0; i < 10; i++) { strcpy(text_data[i][0], "a"); strcpy(text_data[i][1], "xyz"); strcpy(text_data[i][2], "b"); strcpy(text_data[i][3], "xyz"); } ``` ...
strcpy will only copy to a preallocated buffer so try this ``` char text_data[10][4][4]; ``` If you have a double array of String you essentially have a triple array because a string is an array of char.
I have been tasked with converting a C program from an iSeries/AS400 into .NET. It's been awhile since I've looked at C, and I've never used C on an iSeries before. I'm seeing items such as main(int argc, char *argv ??(??)) I'm unsure what the ?? is for. Based upon the usage here, I would assume it is for arrays,...
??(is equivalent to[and??)is equivalent to]. These are called trigraphs, and they're replaced by the preprocessor before anything else is done with the code.Here's a listof other trigraphs.
I, very occasionally, make use of multidimensional arrays, and got curious what the standard says (C11 and/or C++11) about the behavior of indexing with less "dimensions" than the one declared for the array. Given: ``` int a[2][2][2] = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}; ``` Does the standard says what typea[1]is...
m[1]is just of typeint[2][2]. Likewisem[0][1]is justint[2]. And yes, indexing as sub-arrays works the way you think it does.
This question already has answers here:why same code in two technology behaving different [duplicate](3 answers)Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed10 years ago. my code is : ``` code(){ int x=7; x=x++; output x; //prints 8 in C, prints 7 in Java ...
That will print7in Java.x=x++;is equivalent to : ``` int temp = x; x = x + 1; x = temp; ``` The result would have been different if you would have usedprefixoperator ,++x. See for yourself over here:java code;C code. ReadCould anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)to comprehend ...
Suppose you have a DLL with a functionFoothat has either a very large count, i.e.for(int i = 0; i < 1,000,000,000; i++)or a loop of thewhile(something == true)sort and you want to be able to interrupt this function from outside the DLL, what is the safest way to do this? Many thank in advance
Declare a flag inside the DLL, which is tested by the long-runner. Add a method to the DLL that sets this flag. Export this method. Add appropriate protection to be used when accessing the flag. Update The protection mechanics need to be established when the flag is instantiated. For a DLL global flag you would...
I need to write a function which takes 2 words and count its length. I wrote below one but this code only woks for 1st word. How can I improve it to count whole sentence? ``` #include <stdio.h> int findlen(int *s); int main(void) { char string1[80]; printf("Enter a string: "); scanf("%s", string1); printf(...
scanfwill take the one word input only.. (i.e) it breaks when space appears.. Tryfgetsto read the complete string till\n
I have a program that uses err, errx, warn and warnx to alert the user about some unexpected events. Now I have to turn this program into a daemon, so these alerts should go to a well formated log. I have redirected stdout and stderr to a file using freopen(3) but this does not provide enough information in the log. ...
You might like to write wrappers to the functions in question. Those wrappers add the necessary info to the log message and then call the original functions internally. On how to write a wrapper please readanother answer of mine hereand adopt the concept to your needs.
Im asking my self, can i use the BSD sockets with strict aliasing on, without getting undefined behaviour by compiling with gcc? ``` bind(sdListen, (struct sockaddr*)&sockaddr_inIdentifier, sizeof(sockaddr_inIdentifier)) ``` This line of code breaks the strict aliasing rule as far as i know (and gcc gives me the sam...
The cast itself in that line does not break the strict aliasing rule. The rule is only broken if the implementation ofbind()dereferences that pointer without converting it back to the right type. Any strict aliasing problems there are problems for the implementer ofbind(), not the user.
My C program is giving the number "32767" when I enter a letter, but when I enter an integer it tells me the number that I entered. why will my program not tell me what letters I entered? why is it giving me the number "32767"? ``` #include <stdio.h> main() { int number; printf("Enter an integer\n"); s...
Ifscanfdoesn't find what it's looking for (in this case, anint), it will simply return without modifying whatever gets passed in. In other words,scanfwon't changenumber, so it'll have it's old value, which, in this case, is undefined (since it's not initialized).
I have a program that uses err, errx, warn and warnx to alert the user about some unexpected events. Now I have to turn this program into a daemon, so these alerts should go to a well formated log. I have redirected stdout and stderr to a file using freopen(3) but this does not provide enough information in the log. ...
You might like to write wrappers to the functions in question. Those wrappers add the necessary info to the log message and then call the original functions internally. On how to write a wrapper please readanother answer of mine hereand adopt the concept to your needs.
Im asking my self, can i use the BSD sockets with strict aliasing on, without getting undefined behaviour by compiling with gcc? ``` bind(sdListen, (struct sockaddr*)&sockaddr_inIdentifier, sizeof(sockaddr_inIdentifier)) ``` This line of code breaks the strict aliasing rule as far as i know (and gcc gives me the sam...
The cast itself in that line does not break the strict aliasing rule. The rule is only broken if the implementation ofbind()dereferences that pointer without converting it back to the right type. Any strict aliasing problems there are problems for the implementer ofbind(), not the user.
My C program is giving the number "32767" when I enter a letter, but when I enter an integer it tells me the number that I entered. why will my program not tell me what letters I entered? why is it giving me the number "32767"? ``` #include <stdio.h> main() { int number; printf("Enter an integer\n"); s...
Ifscanfdoesn't find what it's looking for (in this case, anint), it will simply return without modifying whatever gets passed in. In other words,scanfwon't changenumber, so it'll have it's old value, which, in this case, is undefined (since it's not initialized).
My C program is giving the number "32767" when I enter a letter, but when I enter an integer it tells me the number that I entered. why will my program not tell me what letters I entered? why is it giving me the number "32767"? ``` #include <stdio.h> main() { int number; printf("Enter an integer\n"); s...
Ifscanfdoesn't find what it's looking for (in this case, anint), it will simply return without modifying whatever gets passed in. In other words,scanfwon't changenumber, so it'll have it's old value, which, in this case, is undefined (since it's not initialized).
Is there any way to find what where the signal that interrupted a call to sleep() came from? I have a ginormous amount of code, and I get this stacktrace from gdb: ``` #0 0x00418422 in __kernel_vsyscall () #1 0x001adfc6 in nanosleep () from /lib/libc.so.6 #2 0x001adde1 in sleep () from /lib/libc.so.6 #3 0x080a3c...
Find what interrupts sleep At the time you attached GDB to the program, thesleepwas in factnotinterrupted by anything -- your stack trace indicates that your program isstillblocked in thesleepsystem call.
Am getting following error when doing linking. ``` /usr/bin/ld: cannot find -lfl ====== cc -g .//obj/add.o .//obj/append.o .//obj/check.o .//obj/compare.o .//obj/free_mem.o .//obj/output.o .//obj/postmosy.o .//obj/premosyy.o .//obj/premosyl.o .//obj/process.o .//obj/store.o -o v2comp -lfl /usr/bin/ld: cannot find -l...
This should help: ``` sudo apt-get install libfl-dev ```
I have a set of lines in a file and each line have several strings seperated by",". How can I split the string based on the delimiter and store the results in a multidimensional array where the first index is the row number in the input file and the second is the column number?
Usestrtok()in string.h header file can be used in C. ``` strtok(char * array, ","); char * array[size of columns][size of rows] pch = strtok (str,","); int i, j; while (pch != NULL) { array[i++][j] = pch; if( i == size of columns - 1){ i = 0; j++; } pch = strtok (NULL, ","); if(j == size of rows -1)...
I have written an openssl program, and now I want to know, if the openssl library calls its own cleanup functions, or if I have to call myself the cleanup functions like SSL_CTX_free and SSL_free?
You have to explicitly call the cleanup functions. I recommend using Valgrind in order to track memory leaks in your program.
Is that a lot of memory access makes slow multithreading? Because I use pthread to multithread a great function who use a lot of memory access. And I have time CPU greater then if I call my function with 1 thread. And proportion of use CPUs is between 50% and 70%.
Don't guess; measure. You don't say what OS you're using, but given pthreads I'm going to guess Linux. Use tools like Valgrind'scallgrindandcachegrindto analyse where your program is spending its time.LTTngcould also help you. Maybeperfalso. Yes, if your program is maxing out your memory bandwidth, or thrashing your...
``` #define address (*((unsigned int *)10)) void main() { unsigned int *p; p = &(address); } ``` 'p' has the value 10. How is the above expression evaluated? Isn't it from inner most brace towards the outermost one? But if it is so then '&' has an lvalue which doesn't make sense. I know that it gets c...
Doesn't it boil down top = &(0)during the compilation? No, not at all: the compiler doesn't know that there is the value 0 at the address 10. It is highly non-portable and is probably supposed to provide a handy identifier -address- which can be used to read a value out of a defined place in memory. I suppose it com...
I have the following code source in C: ``` #include<stdio.h> void main() { int i=0, x=3; while((x---1)) { i++; } printf("%d", i); } ``` How does this while statement work and why does it print 2 instead of 1?
Becausex---1is really justx-- - 1which yields the value ofx - 1before decrementingx. Given thatxhas an initial value of 3, the loop runs 2 times (once with x = 3, once with x = 2, then next time x is 1, sox - 1is 0, and the loop doesn't run anymore). So,istarts at 0 and it's incremented twice, so it ends up being 2....
I am trying to access uninitialized memory, ``` int *ptr; // to this and that *ptr = 8; return 0; ``` I get following exception, Unhandled exception at 0x0041145e in sam2.exe: 0xC0000005: Access violation writing location 0xcccccccc. Now I know0xccccccccis value used for uninitialized pointers in Visual C...
0xC0000005is the access violation error code. Such illegal operations with pointers result in an access violation so this code will be seen. On the other hand0x0041145eisn't a magic number, it's the location of the offending instruction in the executable, and will be different for other programs doing the same thing.
I don't know if this is the best solution but this is all I found after a long search: I would like to search inside an array for mystring and if it's found to show me the country. That's what I've done so far but using arrays of structures is kinda complicated so I kindly request your help ``` char *mystring = "but...
you have to usestrstr()and notstrcmp() ``` int i; for (i=0; i<sizeof(comp)/sizeof(comp[0]); i++) { if (strstr(comp[i].company, mystring)) printf("Country is: %s\n", comp[i].country) } ```
I have this small program which takes input from stdin sample.c ``` #include<stdio.h> main() { int l=0; scanf("%d",&l); printf("\n%d",l); } ``` ofcourse! compiled it: cc sample.c and got a.out and i am trying to run it via php like ``` $runcmd = "./a.out > output.txt"; exec($runcmd,$outp); print_r($outp); ``` ...
take a look at popenhttp://se1.php.net/popen it works a bit like fopen, and when using fwrite, insted of writing to a file you can write to a prosses stdin insted. ``` $runcmd = "./a.out > output.txt"; $process_stdin = popen($runcmd, 'w'); fwrite($process_stdin, "text to send to process"); pclose($process_stdin); ``...
Hi this is an interview question. For any given number calculate next number which is divisible by 8. i.e. If given number is43, our algorithm should produce48as result. If number is already divisible by8it should sayNumber already divisible by 8and produce next number divisible by 8. I suggest them that any number...
You're on the right track. ``` int next8(int n) { int bits = n & 7; // give us the distance to the previous 8 if (bits == 0) printf("Number already divisible by 8"); return n + (8-bits); } ``` (Note: I hate it when functions that are supposed to be pure print something, but the task demands so. Sorry.)
Am getting following error when doing linking. ``` /usr/bin/ld: cannot find -lfl ====== cc -g .//obj/add.o .//obj/append.o .//obj/check.o .//obj/compare.o .//obj/free_mem.o .//obj/output.o .//obj/postmosy.o .//obj/premosyy.o .//obj/premosyl.o .//obj/process.o .//obj/store.o -o v2comp -lfl /usr/bin/ld: cannot find -l...
This should help: ``` sudo apt-get install libfl-dev ```
I have a set of lines in a file and each line have several strings seperated by",". How can I split the string based on the delimiter and store the results in a multidimensional array where the first index is the row number in the input file and the second is the column number?
Usestrtok()in string.h header file can be used in C. ``` strtok(char * array, ","); char * array[size of columns][size of rows] pch = strtok (str,","); int i, j; while (pch != NULL) { array[i++][j] = pch; if( i == size of columns - 1){ i = 0; j++; } pch = strtok (NULL, ","); if(j == size of rows -1)...
I have written an openssl program, and now I want to know, if the openssl library calls its own cleanup functions, or if I have to call myself the cleanup functions like SSL_CTX_free and SSL_free?
You have to explicitly call the cleanup functions. I recommend using Valgrind in order to track memory leaks in your program.
Is that a lot of memory access makes slow multithreading? Because I use pthread to multithread a great function who use a lot of memory access. And I have time CPU greater then if I call my function with 1 thread. And proportion of use CPUs is between 50% and 70%.
Don't guess; measure. You don't say what OS you're using, but given pthreads I'm going to guess Linux. Use tools like Valgrind'scallgrindandcachegrindto analyse where your program is spending its time.LTTngcould also help you. Maybeperfalso. Yes, if your program is maxing out your memory bandwidth, or thrashing your...
``` #define address (*((unsigned int *)10)) void main() { unsigned int *p; p = &(address); } ``` 'p' has the value 10. How is the above expression evaluated? Isn't it from inner most brace towards the outermost one? But if it is so then '&' has an lvalue which doesn't make sense. I know that it gets c...
Doesn't it boil down top = &(0)during the compilation? No, not at all: the compiler doesn't know that there is the value 0 at the address 10. It is highly non-portable and is probably supposed to provide a handy identifier -address- which can be used to read a value out of a defined place in memory. I suppose it com...
I have the following code source in C: ``` #include<stdio.h> void main() { int i=0, x=3; while((x---1)) { i++; } printf("%d", i); } ``` How does this while statement work and why does it print 2 instead of 1?
Becausex---1is really justx-- - 1which yields the value ofx - 1before decrementingx. Given thatxhas an initial value of 3, the loop runs 2 times (once with x = 3, once with x = 2, then next time x is 1, sox - 1is 0, and the loop doesn't run anymore). So,istarts at 0 and it's incremented twice, so it ends up being 2....
I am trying to access uninitialized memory, ``` int *ptr; // to this and that *ptr = 8; return 0; ``` I get following exception, Unhandled exception at 0x0041145e in sam2.exe: 0xC0000005: Access violation writing location 0xcccccccc. Now I know0xccccccccis value used for uninitialized pointers in Visual C...
0xC0000005is the access violation error code. Such illegal operations with pointers result in an access violation so this code will be seen. On the other hand0x0041145eisn't a magic number, it's the location of the offending instruction in the executable, and will be different for other programs doing the same thing.
I don't know if this is the best solution but this is all I found after a long search: I would like to search inside an array for mystring and if it's found to show me the country. That's what I've done so far but using arrays of structures is kinda complicated so I kindly request your help ``` char *mystring = "but...
you have to usestrstr()and notstrcmp() ``` int i; for (i=0; i<sizeof(comp)/sizeof(comp[0]); i++) { if (strstr(comp[i].company, mystring)) printf("Country is: %s\n", comp[i].country) } ```
I have this small program which takes input from stdin sample.c ``` #include<stdio.h> main() { int l=0; scanf("%d",&l); printf("\n%d",l); } ``` ofcourse! compiled it: cc sample.c and got a.out and i am trying to run it via php like ``` $runcmd = "./a.out > output.txt"; exec($runcmd,$outp); print_r($outp); ``` ...
take a look at popenhttp://se1.php.net/popen it works a bit like fopen, and when using fwrite, insted of writing to a file you can write to a prosses stdin insted. ``` $runcmd = "./a.out > output.txt"; $process_stdin = popen($runcmd, 'w'); fwrite($process_stdin, "text to send to process"); pclose($process_stdin); ``...
Hi this is an interview question. For any given number calculate next number which is divisible by 8. i.e. If given number is43, our algorithm should produce48as result. If number is already divisible by8it should sayNumber already divisible by 8and produce next number divisible by 8. I suggest them that any number...
You're on the right track. ``` int next8(int n) { int bits = n & 7; // give us the distance to the previous 8 if (bits == 0) printf("Number already divisible by 8"); return n + (8-bits); } ``` (Note: I hate it when functions that are supposed to be pure print something, but the task demands so. Sorry.)
Is that a lot of memory access makes slow multithreading? Because I use pthread to multithread a great function who use a lot of memory access. And I have time CPU greater then if I call my function with 1 thread. And proportion of use CPUs is between 50% and 70%.
Don't guess; measure. You don't say what OS you're using, but given pthreads I'm going to guess Linux. Use tools like Valgrind'scallgrindandcachegrindto analyse where your program is spending its time.LTTngcould also help you. Maybeperfalso. Yes, if your program is maxing out your memory bandwidth, or thrashing your...
``` #define address (*((unsigned int *)10)) void main() { unsigned int *p; p = &(address); } ``` 'p' has the value 10. How is the above expression evaluated? Isn't it from inner most brace towards the outermost one? But if it is so then '&' has an lvalue which doesn't make sense. I know that it gets c...
Doesn't it boil down top = &(0)during the compilation? No, not at all: the compiler doesn't know that there is the value 0 at the address 10. It is highly non-portable and is probably supposed to provide a handy identifier -address- which can be used to read a value out of a defined place in memory. I suppose it com...
I have the following code source in C: ``` #include<stdio.h> void main() { int i=0, x=3; while((x---1)) { i++; } printf("%d", i); } ``` How does this while statement work and why does it print 2 instead of 1?
Becausex---1is really justx-- - 1which yields the value ofx - 1before decrementingx. Given thatxhas an initial value of 3, the loop runs 2 times (once with x = 3, once with x = 2, then next time x is 1, sox - 1is 0, and the loop doesn't run anymore). So,istarts at 0 and it's incremented twice, so it ends up being 2....
I am trying to access uninitialized memory, ``` int *ptr; // to this and that *ptr = 8; return 0; ``` I get following exception, Unhandled exception at 0x0041145e in sam2.exe: 0xC0000005: Access violation writing location 0xcccccccc. Now I know0xccccccccis value used for uninitialized pointers in Visual C...
0xC0000005is the access violation error code. Such illegal operations with pointers result in an access violation so this code will be seen. On the other hand0x0041145eisn't a magic number, it's the location of the offending instruction in the executable, and will be different for other programs doing the same thing.
I don't know if this is the best solution but this is all I found after a long search: I would like to search inside an array for mystring and if it's found to show me the country. That's what I've done so far but using arrays of structures is kinda complicated so I kindly request your help ``` char *mystring = "but...
you have to usestrstr()and notstrcmp() ``` int i; for (i=0; i<sizeof(comp)/sizeof(comp[0]); i++) { if (strstr(comp[i].company, mystring)) printf("Country is: %s\n", comp[i].country) } ```
I have this small program which takes input from stdin sample.c ``` #include<stdio.h> main() { int l=0; scanf("%d",&l); printf("\n%d",l); } ``` ofcourse! compiled it: cc sample.c and got a.out and i am trying to run it via php like ``` $runcmd = "./a.out > output.txt"; exec($runcmd,$outp); print_r($outp); ``` ...
take a look at popenhttp://se1.php.net/popen it works a bit like fopen, and when using fwrite, insted of writing to a file you can write to a prosses stdin insted. ``` $runcmd = "./a.out > output.txt"; $process_stdin = popen($runcmd, 'w'); fwrite($process_stdin, "text to send to process"); pclose($process_stdin); ``...
Hi this is an interview question. For any given number calculate next number which is divisible by 8. i.e. If given number is43, our algorithm should produce48as result. If number is already divisible by8it should sayNumber already divisible by 8and produce next number divisible by 8. I suggest them that any number...
You're on the right track. ``` int next8(int n) { int bits = n & 7; // give us the distance to the previous 8 if (bits == 0) printf("Number already divisible by 8"); return n + (8-bits); } ``` (Note: I hate it when functions that are supposed to be pure print something, but the task demands so. Sorry.)
I know the following is valid code: ``` #define SOMEMACRO 10 int arr[SOMEMACRO]; ``` which would result asint arr[10]. If I wanted to make an array 2x size of that (and still need the original macro elsewhere), is this valid code? ``` #define SOMEMACRO 10 int arr[2 * SOMEMACRO]; ``` which would beint arr[2 * 10]a...
Yes it will work.MACRO will be placed as it is at compilation soa[2*SOMEMACRO]will becomea[2*10]which is perfectly valid. To check what is preprocessed you can usecc -E foo.coption
I have stumbled upon a persistent problem, that doesn't seem to have a rational explanation. The problem seems to lie inside a for loop that goesfor (i = size - 1; i >= 0; i--) {etc.}wheresizeis the size of a file stored in a memory buffer andiis an unsigned integer. Instead of stopping wheni == 0, it wraps around - t...
An unsigned integer is always>= 0. ``` for (i = size - 1; i >= 0; i--) {etc.} ``` is an infinite loop ifiis anunsigned int.
For example: ``` char a[] = "abc\0"; ``` Does standard C say that another byte of value0must be appended even if the string already has a zero at the end? So, issizeof(a)equal to 4 or 5?
All string literals have an implicit null-terminator, irrespective of the content of the string. The standard (6.4.5 String Literals) says: A byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. So, the string literal"abc\0"contains the implicit...
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.Closed9 years ago.Improve this question I am really curious that it is possible to recover all codes from so(Shared Object) file. I made libxxx.so...
You can get certain things back such as method names, and number of arguments from those variables, but no, you cannot decompile a binary .so file back to its original source.
My machine is a Windows 8 machine. I want to read the "UpperFilters" key fromHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{36fc9e60-c465-11cf-8056-444553540000}from my custom driver to get the presence of filter drivers over USB devices.
I haven't written a driver since the days of XP, but assuming you're talking about a kernel mode driver I belive you wantZwOpenKey,ZwQueryValueKeyandZwClose. General guidancehere.
I'm writing a Python-based [web] application that needs to be able to read and write EXIF data. libexifseems to have all the right ingredients, but I can't work out how (or if) I could access it access it by using Python'sctypes library? I'm new to C, suppose I needseea.sofor this to work?
You need to be running on an os that you can obtain the required library, to download the .h files, (usually the -dev package gives you these). Then you need to work your way through the ctypes tutorial foundherewhich explains all the steps you need to take.
I am trying to implement a bitonic sort as part of a closest pair d&c algorithm in cuda and I came across Thrust library. I noticed that it implements radix sort which, from what I have read, is the fastest for integers but is this the same for floats? Would it be better to implement a bitonic sort only for floats or ...
You should not write your own sorting algorithm if you're interested in speed. Sorting is an operation that has received considerable attention, and you're not likely to be able to come up with something as fast as what has been written already, regardless of whether you are usingintorfloat. You should consider usin...
In the libraryFreeImagePlus, inFreeImage.h, there is a funny#definewhich seems to create atypedefand anenumwith the same name: ``` #define FI_ENUM(x) typedef int x; enum x ``` This is expanded by the preprocessor to code like: ``` typedef int FREE_IMAGE_FILTER; enum FREE_IMAGE_FILTER { FILTER_BOX = 0, FILTER...
Names of structures, unions and enumerations lives in their own namespace. That's why you can declare astruct/union/enumvariable with the same name as the actualstruct/union/enum. And it's not the name of the completeenum(e.g. forenum XI mean theX) that has to be compatible with an integer, it's the namesinsidethe en...
I just was looking up funciton attributes for gcc (http://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Function-Attributes.html) and came across thereturns_twiceattribute. And I am absolutely clueless in what case a function can return twice... I looked up quickly the mentionedvfork()andsetjmp()but continue without an idea ...
Thesetjmpfunction is analogous to creating alabel(in thegotosense), as such you will first return fromsetjmpwhen you set the label, and then each time that you actually jump to it. If it seems weird, rest assured, you should not be usingsetjmpin your daily programming. Or actually... you should probably not be using ...
I need to create a C compatible (friendly) return type so that my C++ functions can be used to work with C-based functions. How I can convert a vector ofwstringto awchar_t**array?
You can iterate through the wstring vector and add eachwstring::c_str()to yourwchart_t**array.
I am trying to passstructpointer in function. I have atypedefin file1.h, and want to only include that header to file2.c, because file2.h only need pointer. In C++ I would just write like I did here, but using C99 it doesn't work. If someone has any suggestions how to passstructpointer without full definition it would...
I think you just have to name your structure, and do a forward declaration of it and after re typedef it. First file: ``` typedef struct structName {} t_structName; ``` Second file: ``` struct stuctName; typedef struct structName t_structName ```
I'm writing a Python-based [web] application that needs to be able to read and write EXIF data. libexifseems to have all the right ingredients, but I can't work out how (or if) I could access it access it by using Python'sctypes library? I'm new to C, suppose I needseea.sofor this to work?
You need to be running on an os that you can obtain the required library, to download the .h files, (usually the -dev package gives you these). Then you need to work your way through the ctypes tutorial foundherewhich explains all the steps you need to take.
I am trying to implement a bitonic sort as part of a closest pair d&c algorithm in cuda and I came across Thrust library. I noticed that it implements radix sort which, from what I have read, is the fastest for integers but is this the same for floats? Would it be better to implement a bitonic sort only for floats or ...
You should not write your own sorting algorithm if you're interested in speed. Sorting is an operation that has received considerable attention, and you're not likely to be able to come up with something as fast as what has been written already, regardless of whether you are usingintorfloat. You should consider usin...
In the libraryFreeImagePlus, inFreeImage.h, there is a funny#definewhich seems to create atypedefand anenumwith the same name: ``` #define FI_ENUM(x) typedef int x; enum x ``` This is expanded by the preprocessor to code like: ``` typedef int FREE_IMAGE_FILTER; enum FREE_IMAGE_FILTER { FILTER_BOX = 0, FILTER...
Names of structures, unions and enumerations lives in their own namespace. That's why you can declare astruct/union/enumvariable with the same name as the actualstruct/union/enum. And it's not the name of the completeenum(e.g. forenum XI mean theX) that has to be compatible with an integer, it's the namesinsidethe en...
I just was looking up funciton attributes for gcc (http://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Function-Attributes.html) and came across thereturns_twiceattribute. And I am absolutely clueless in what case a function can return twice... I looked up quickly the mentionedvfork()andsetjmp()but continue without an idea ...
Thesetjmpfunction is analogous to creating alabel(in thegotosense), as such you will first return fromsetjmpwhen you set the label, and then each time that you actually jump to it. If it seems weird, rest assured, you should not be usingsetjmpin your daily programming. Or actually... you should probably not be using ...
I need to create a C compatible (friendly) return type so that my C++ functions can be used to work with C-based functions. How I can convert a vector ofwstringto awchar_t**array?
You can iterate through the wstring vector and add eachwstring::c_str()to yourwchart_t**array.
I am trying to passstructpointer in function. I have atypedefin file1.h, and want to only include that header to file2.c, because file2.h only need pointer. In C++ I would just write like I did here, but using C99 it doesn't work. If someone has any suggestions how to passstructpointer without full definition it would...
I think you just have to name your structure, and do a forward declaration of it and after re typedef it. First file: ``` typedef struct structName {} t_structName; ``` Second file: ``` struct stuctName; typedef struct structName t_structName ```
So, I have one function like the following: ``` void myfunction1(int *number) { ... } ``` And I have: ``` void myfunction2(int *number) { ... myfunction1(&number); } ``` When I run the code I get the error: ``` warning: passing argument 1 of ‘myfunction1’ from incompatible pointer type ``` So I chang...
numberalready has typeint*so you can pass it directly tomyfunction1withmyfunction1(number). Themallocerror has nothing to do with any code that you have shown.
I am writing a little PDF library in C. When generating PDF source code that is responsible for rendering text, I need to know how much space the rendered text occupies in order to render the next paragraph correctly. How do I find out? Thank you!
The mechanisms and math of PDF text rendering are exhaustively explained in the PDF specificationISO 32000-1. Most important are chapters 8Graphicsand 9Text. Essentially you need to know the current graphic state (which should be easy because you after all are the one who creates the PDF) and the metrics of the font ...
What is the height of a complete binary tree with N nodes? I'm looking for an exact answer, and either a floor or ceiling value.
It'sCEIL(log2(n+1))-1 1 node gives log2(2) = 13 nodes gives log2(4) = 27 nodes gives log2(8) = 315 nodes gives log2(16) = 4... EDIT: According to wikipedia, the root node (rather un-intuitively?) does not count in the height, so the formula would beCEIL(log2(n+1))-1.
I've created a new window and want to move it to the center of the screen, and how am I supposed to do it? I've tried below ``` gtk_widget_hide (GTK_WIDGET (window)); gtk_window_set_position (window, GTK_WIN_POS_CENTER); gtk_widget_show_all (GTK_WIDGET (window)); ``` but it seems that thegtk_window_set_position (win...
you must usegtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER_ALWAYS):)
I have tried to run the following code in C that uses stdarg.h but I can't get it to work for some reason. I have no experience using the variable argument lists so someone please help! ``` #include <stdio.h> #include <stdlib.h> #include <stdarg.h> int add_stuff_together(int numb_count, ...); int main() { int x...
Yoursumvariable is not initialized so its value can default to anything. Also note that you dont use theva_end()macro, and you should do.
I am trying to read a file from the command line passed as input. No not the filename. I'm not expecting the user to input a filename on the command-line, so that I could open it like this :fopen(argv[1], "r");. I am expecting a file like this :myprogram < file_as_input. So whatever should go into argv is the content...
When a program is invoked like this./a.out < file, the content of the file will be available on the standard input:stdin. That means that you can read this content by reading the standard input. For example: read(0, buffer, LEN)would read the from your file.getchar()would return a char from your file.
In a gcc makefile, you can use the -D flag to specify a define in the compiled program. For example, instead of putting #define SOMETHING, you can specify -DSOMETHING in the makefile. What is the equivalent of this in SCons?
I believe you want theCPPDEFINESconstruction variable. Seethe SCons documentation pagefor some more details, underCPPDEFINES.
``` while(count < 30000000){ malloc(24); count++; } ``` the above code runs in about 170 ms on my computer compiled with gcc -O0. However, compiling with -Ox where x > 0, the optimizer cleverly figures out that the memory being requested will never be used and so it is excluded from the optimized executable. ...
Well the compiler seesmallocreturn value is never used so it optimizes it out. If you want to preventmalloccall to be optimzed out even in-O3you can use thevolatilequalifier: ``` while(count < 30000000){ void * volatile p = malloc(24); count++; } ```
I am creating a simple Tic Tac Toe for C, and here is a particular function which I am having a problem with. This is supposed to let the user select 'X' or 'O', and for the most art it works. However, if I enter a wrong symbol, it prints the statement: "Invalid symbol, please re-enter: " twice. Why andhowcan I fi...
The problem cause is related to the newline charachter usescanf()in this way instead of usinggetchar() ``` scanf(" %c", &user); ```
guys what's the meaning of -> in linked list?? explain with example please I've searched online and none of the site tells what's this thing and just go straight to coding example ``` start=start->next; // (a) start->prev = NULL; // (b) ``` is the meaning of (a) moving start to next node and then assign the next n...
The->symbol is an operator to select an element from a data structure pointed to by a pointer. So suppose you have a pointer defined asmystruct *pand it points to amystructinstantiation. Suppose also thatmystructdeclares a variableiof, say, typeint. Then the following notations are equivalent: ``` (*p).i = 2; ``` or...
Why the ternary operator cannot be used to initialize a structure type, while it can be used to initialize a base type likeint? Example code : ``` #include <stdio.h> #define ODD 1 int main(int argc, const char *argv[]) { static struct pair_str { int first; int second; } pair = ( ODD ) ? {1,3} : {2,4}...
Sure, use C99 compound literals: ``` pair = odd ? (struct pair_str){ 1, 3 } : (struct pair_str){ 2, 4 }; ```
``` #include<stdio.h> int main() { printf("hi"); } ``` which will be executed first main or header file? does main program will execute first and include the contents of header file?
#includemeans textual insertion of the file at exactly the line where the#includeis found. That is done by the preprocessor, so the compiler doesn't see the#includecommand itself anymore. In your case that means that first all code from stdio.h iscompiledand then your functionmain(). But nevertheless programexecutiona...
I have an iphone app. I made my source code as boost library. Is there any possibility to embed my library to my android app? I am using eclipse. Can any one send any link about this. At least a simple C or C++ library embedding to android and using those functions in my android app?
You need to use Android NDK tool chain for cross compiling the library. This link shows how to use it - "http://www.cmumobileapps.com/2011/08/31/compiling-open-source-libraries-with-android-ndk-part-1/" If you need support of STL, RTTI, C++ exception, then there's a patched up NDK available athttp://www.crystax.net/...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do...
These links will help. There is other good stuff at the site as well. And it is C oriented. http://cslibrary.stanford.edu/103/http://cslibrary.stanford.edu/102/
How can I store the result ofSerial.readBytesUntil(character, buffer, length)in a buffer while I don't know the length of the incoming message ?
Here is a little code that makes use ofrealloc()to keep growing your buffer. You will have tofree()when you're done withbuf. ``` int length = 8; char * buf = malloc(length); int total_read = 0; total_read = Serial.readBytesUntil(character, buf, length); while(length == total_read) { length *= 2; buf = reallo...
In order to catch SIGURG associated with accepted connection, one would have to do fcntl call to get the socket ownership. Does it mean that a process creating a socket is not assigned as the socket's owner by default? And, if so, who is the initial owner? Thanks PS the question is in relation to Figure 24.11 of Netw...
No one is the initial owner. And if you set a process group ID withF_SETOWN, the socket goes from no "owner" to multiple "owners". The issue here is really that "owner" is a terrible choice of nomenclature, since the actual effect is more about asking for notifications of urgent data than taking ownership of the socke...
``` while(count < 30000000){ malloc(24); count++; } ``` the above code runs in about 170 ms on my computer compiled with gcc -O0. However, compiling with -Ox where x > 0, the optimizer cleverly figures out that the memory being requested will never be used and so it is excluded from the optimized executable. ...
Well the compiler seesmallocreturn value is never used so it optimizes it out. If you want to preventmalloccall to be optimzed out even in-O3you can use thevolatilequalifier: ``` while(count < 30000000){ void * volatile p = malloc(24); count++; } ```
I am creating a simple Tic Tac Toe for C, and here is a particular function which I am having a problem with. This is supposed to let the user select 'X' or 'O', and for the most art it works. However, if I enter a wrong symbol, it prints the statement: "Invalid symbol, please re-enter: " twice. Why andhowcan I fi...
The problem cause is related to the newline charachter usescanf()in this way instead of usinggetchar() ``` scanf(" %c", &user); ```
guys what's the meaning of -> in linked list?? explain with example please I've searched online and none of the site tells what's this thing and just go straight to coding example ``` start=start->next; // (a) start->prev = NULL; // (b) ``` is the meaning of (a) moving start to next node and then assign the next n...
The->symbol is an operator to select an element from a data structure pointed to by a pointer. So suppose you have a pointer defined asmystruct *pand it points to amystructinstantiation. Suppose also thatmystructdeclares a variableiof, say, typeint. Then the following notations are equivalent: ``` (*p).i = 2; ``` or...
Why the ternary operator cannot be used to initialize a structure type, while it can be used to initialize a base type likeint? Example code : ``` #include <stdio.h> #define ODD 1 int main(int argc, const char *argv[]) { static struct pair_str { int first; int second; } pair = ( ODD ) ? {1,3} : {2,4}...
Sure, use C99 compound literals: ``` pair = odd ? (struct pair_str){ 1, 3 } : (struct pair_str){ 2, 4 }; ```
``` #include<stdio.h> int main() { printf("hi"); } ``` which will be executed first main or header file? does main program will execute first and include the contents of header file?
#includemeans textual insertion of the file at exactly the line where the#includeis found. That is done by the preprocessor, so the compiler doesn't see the#includecommand itself anymore. In your case that means that first all code from stdio.h iscompiledand then your functionmain(). But nevertheless programexecutiona...
I have an iphone app. I made my source code as boost library. Is there any possibility to embed my library to my android app? I am using eclipse. Can any one send any link about this. At least a simple C or C++ library embedding to android and using those functions in my android app?
You need to use Android NDK tool chain for cross compiling the library. This link shows how to use it - "http://www.cmumobileapps.com/2011/08/31/compiling-open-source-libraries-with-android-ndk-part-1/" If you need support of STL, RTTI, C++ exception, then there's a patched up NDK available athttp://www.crystax.net/...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do...
These links will help. There is other good stuff at the site as well. And it is C oriented. http://cslibrary.stanford.edu/103/http://cslibrary.stanford.edu/102/
How can I store the result ofSerial.readBytesUntil(character, buffer, length)in a buffer while I don't know the length of the incoming message ?
Here is a little code that makes use ofrealloc()to keep growing your buffer. You will have tofree()when you're done withbuf. ``` int length = 8; char * buf = malloc(length); int total_read = 0; total_read = Serial.readBytesUntil(character, buf, length); while(length == total_read) { length *= 2; buf = reallo...
In order to catch SIGURG associated with accepted connection, one would have to do fcntl call to get the socket ownership. Does it mean that a process creating a socket is not assigned as the socket's owner by default? And, if so, who is the initial owner? Thanks PS the question is in relation to Figure 24.11 of Netw...
No one is the initial owner. And if you set a process group ID withF_SETOWN, the socket goes from no "owner" to multiple "owners". The issue here is really that "owner" is a terrible choice of nomenclature, since the actual effect is more about asking for notifications of urgent data than taking ownership of the socke...