question
stringlengths
25
894
answer
stringlengths
4
863
In the following sample code, why sample_breaks fails to compile? ``` #define ONE_FRAME_OF_30FPS_2 = 1.0/30.0; void sample_works() { double partOfSecondAVFoundationNumber = 2 * 1.0/30.0; } void sample_breaks() { double partOfSecondAVFoundationNumber = 2 * ONE_FRAME_OF_30FPS_2; } ```
It becomes this: ``` void sample_breaks() { double partOfSecondAVFoundationNumber = 2 * = 1.0/30.0;; } ``` after preprocessing. So you would expect an error. Change to ``` #define ONE_FRAME_OF_30FPS_2 (1.0/30.0) ``` instead.
I have written a program which shows me all values of this math expression: (ABC)=(AB)*(AB)-C*C. A,B,C are the digits of the number. The question is: How can i write program that shows me only FIRST value of this expression? Thanks Code: ``` #include <stdio.h> main() { int a,b,c; for(a=1;a<10;a++) ...
Try to add count, then check it. ``` #include <stdio.h> main() { int a,b,c,count; count = 0; for(a=1;a<10;a++) for(b=0;b<10;b++) for(c=0;c<10;c++) if((a*100+b*10+c*1)==(a*10+b*1)*(a*10+b*1)-(c*c)) count++; if(count == 1) { printf("%d%d%d\n",a,b,c); } system("pause"); } ```
I have my server program binding fine to 0.0.0.0 (INADDR_ANY) or 127.0.0.1 (INADDR_LOOPBACK), however I want the program to listen on my local network IP (192.168.1.24) and I keep getting this error: Error opening the listening port 8888 (Raw TCP output): Cannot assign requested address Here is the relevant code: `...
The IP you use is: 200.168.1.24 Use: ``` sa.sin_addr.s_addr = inet_addr("192.168.1.24"); ``` instead.Make sure the port isn't already in use. (use the program netstat) Have you closed the socket correctly, at tests before?
The company I'm working for have development rules for C development on embedded target. One is : It is recommended to not allocate any storage space in the header files. I'm not sure what it means, the person who wrote it is not around and the other developers don't really care, so I am asking here. What I underst...
What is wrong is that external variables get doubly defined, whilestaticones get defined for each module that includes the header, wasting space (unless they get optimized away).
We have a application(native c/c++library) which is compiled based on user requirements and system configuration, currently we compile the library with gcc and response it synchronously or asynchronously to the user, but it's happening localy.Now we have integrated the web part with app engine for now.QuestionHow may ...
You can integrate your GAE application with Compute engine. At the recent google cloud event, there were several demos on how to integrate between appengine and compute engine. This may be a goodstarting point. Or look fora good sample on githubon how to integrate compute engine and app engine.
This question already has answers here:What does ~0 do?(4 answers)Closed9 years ago. I see this type data in code program. But I don't know this type data. What means this type of data? ``` (uint16_t)~0U ```
``` (uint16_t) ~ 0 U ^ ^ ^ ^ | | | |____ unsigned constant | | |______ the number 0 | |________ bitwise not operator |______________ casting to 16 bits integer ``` As a result you get a 0xffff
I need to find the device file (/dev/tty*or/dev/pts/*) connected to the standard input of any process on my system. I want to implement something similar to thetty(1)program but which works for any process. How do I do this? This is on Linux. The closest I've gotten is to parse the/proc/pid/statfile and read out the ...
On Linux, you may just dols -L /proc/pid/fd/0to get the tty attached with the stdin of the process with process idpid.
how can we add a number of type gint to a TextBuffer in gtk+3? gtk_text_buffer_set_text has argument of type gchar but I want to set integer of type gint
When doing I/O in C, you generally use strings. Since this is a form of I/O, it's to be expected that you need to format the number into a string first. This is also nice since formatting a number into a string can be done many ways (different bases, number of digits, padding, and so on) so keeping this on the applic...
When I read from a SOCK_STREAM socket like this: ``` int t; while ((t = read(clientsocket, buff, 128) > 0)) { write(1, buff, t); } ``` read always return 1, but if I look into buff with gdb I can see the whole line I sent. I'm using netcat to send data to the server.
This is incorrect due tooperator precedence: ``` while ((t = read(clientsocket, buff, 128) > 0)) ``` and results intbeing assigned the result ofread(clientsocket, buff, 128) > 0, which will be0or1. To correct, change to: ``` while ((t = read(clientsocket, buff, 128)) > 0) ```
How can I use printf in C to display the full length of a double. Consider ``` int main(){ double x = 0.00000000000001; printf("x: %f \n", x); } ``` The result I get is "i: 0.000000", however from what I read %f is the correct format specifier and doubles should have 15-17 significant figures therefore I don't u...
Fromhttp://linux.die.net/man/3/printf: f, FThe double argument is rounded and converted to decimal notation in the style [-]ddd.ddd, where the number of digits after the decimal-point character is equal to the precision specification.If the precision is missing, it is taken as 6;if the precision is explicitly...
I have coded the following function that will reverse a String in C: ``` void reverse(char *str) { int length = strlen(str) - 1; for (int i=0; i < length/2; i++) { char tmp = str[i]; str[i] = str[length - i]; str[length - i] = tmp; } } ``` This...
You can not do that, string literals are constants in C Perhaps, you need to copy the string, much like you do it in your first example, where you initialize a char array using a string literal.
I have the following code below. ``` typedef struct person Person; Person { char* name; int age; }; ``` From what I understand, typedef will substitute "struct person" with Person. So when making the struct, it is equal to writing : ``` struct person { char* name; int age; ...
Do it like this ``` typedef struct person Person; struct person { char* name; int age; }; ``` Then you can usePersonfor allusagesof thestruct. also there is no need in different capitalization ``` typedef struct person person; ``` would do equally well.
What is the inner working ofgetchar_unlocked()?Why is it thread unsafe?And why it is not employed in windows POSIX?
getchar_unlocked() is not threadsafe, because it might manipulates internal data structures without locking or any other type of synchronisation. For any more detailled answer, you must look at the exact implementation in question. Omitting thread safety (and being inlined/a preprocessor define) is what makes it fast...
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed9 years ago.Improve this question We can input decimal, octal and hexadecimal numbers using scanf. We can output decim...
Because any competent programmer can easily do binary number output and input himself, it's too verbose, and hexadecimal is just as good for flags and an easy transformation?
I have two light sources, three spheres and two triangles. Spheres placed on two triangles. I alrady did intersectSphere and computeColorSphere functions. I somehow started implementing intersectTriangle and computeColorTriangle functions. How should it be different from Sphere functions ? and how can i implement sha...
Computing cast shadows is done as follows: when you hit a surface with a ray and apply the illumination model there, you add the contribution of all light sources (like you did); but you need to check if there is no obstacle to the light sources by casting secondary rays from the hit point to the sources. If you find ...
I have a pointer problem which I don't understand, I hope you can help me. ``` int main() { int tab[] = {1,2,3}; int *ptr; ptr=tab; // this is where my doubt lies cout << &ptr << "," << ptr << "," << *ptr << "," << &tab << "," << tab << "," << *tab << endl; return(0); } ``` to put the pointer poi...
C arrays decay into pointers whenever they can. With the line ``` ptr=tab; ``` you might encounter similar behavior to ``` ptr=&tab; ``` but the types are different: in the first case you're asking for an int pointer, in the latter you're asking for a pointer to an array of ints with a specific type.
I have a program that read 2 strings from keyboard and string1 will be replaced by string2. The problem is program crashes right after I press Enter. Can everybody explain what's wrong in my program? Thank you! ``` #include<stdio.h> #define SIZE 80 void mystery1( char *s1, const char *s2 ); int main( void) { ch...
``` scanf("%79s%79s", string1, string2); ``` This solved the problem for me. Or may use: ``` scanf_s("%79s %79s", string1,80, string2, 80); ```
What is the security hole intmpfileand how doestmpfile_ssolve it?
In this case, it appears to fall under the "Enhanced error reporting" category of upgrades to the Windows CRT. In this case, it basically means that it will return a status value and fill out a pre-givenFILEpointer, rather than just returning aFILEpointer. I doubt there was actually a security flaw withtmpfile, more ...
I will have multiple 2d int arrays.. ``` int[5][5] A; int[5][5] B; int[5][5] C; ``` but how many I need is dependent on a parameter decided on runtime. How would I create a dynamic amount of 2D arrays and manage them?
In C you may use Variable Length Arrays (VLA). So you can declare one three dimensional array the left dimension of which will specify the number of two dimensional arrays. For example ``` #include <stdlib.h> int main( int argc, char * argv[] ) { // some check that the command line parameter was specified int...
I have the following code: ``` #include <stdio.h> void changeValue(char str[]) { str[2] = 'a'; } int main() { char a[]="Hello world"; changeValue(a); printf("%s", a); } ``` And I am trying to understand how this is working. Why when passing the array named 'a' it is being passed by reference? So, the...
In many situations (including passing them as function arguments) arrays are converted to a pointer to their first element. So, what you are passing is not an array. In fact, the syntax used in the prototype is just eye candy ``` void changeValue(char str[]); void changeValue(char *str); ``` the above prototypes ar...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question appears to be off-topic becauseit lacks sufficient information to diagnose the problem.Describe your problem in more detail orinclude a minimal examplein the question itself.Closed9 years ago.Improve this q...
First,the LDD3 chapter on block devicesfor the explanations, thensome sample codebased on it.
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 creating program in C which allocates dynamic memory for array and I made function which shows those n...
``` int * data = malloc(count * sizeof(int)); if (data) printf("Allocation succeeded"); else printf("Allocation failed"); ```
If, for instance only 1 thread can access aCritical Sectionat a time, why do we needEventsto synch 2 threads to read/write through it?
There is some overlap in how they can be used, but there are also some unique features to both: Critical sections cannot be used across processes, whereas events can.A single manual-reset event can be used to release multiple threads at once. A critical section cannot.Events are compatible withWaitForSingleObject()et...
In c ~ is 1's complement operator. This is equivalent to: ~a = -b + 1 So, a - ~b -1 = a-(-b + 1) + 1 = a + b – 1 + 1 = a + b Can anyone explains this to me?
From elementary school math we know ``` a = -(-a); ``` From twos complement we know that ``` -a = (~a) + 1 (invert and add one) ``` so we know that ``` a + b = a - (-b) elementary math = a - (~b + 1) twos complement = a - (~b) - 1 distribute the negative (elementary math) ```
I have a program where i need to supply 2 different streams as input. If I only needed one stream as input, I could use stdin like so ``` ./a.out <file1 fgets(buf,1000,stdin) ``` Is it possible to do something like ``` ./a.out --file1 <(cat file1) --file2 <(cat file2) FILE *fp1 = fdopen(3,"r"); FILE *fp2 = fdopen...
If you are using bash as your shell, you can do the following: ``` ./a.out 3< file1 4< file2 ```
About how many clock cycles does it take to make a simple, non-blocking system call on Linux? Would I expect anything different from OS X? I wonder about calls such assetsockopt, which might be used to provide an optional hint to improve performance, yet has its own intrinsic cost.
It really depends on the system call and on the hardware. The overhead of making a syscall is not very big!thisgives less than a microsecond (i.e. a hundred processor clock cycles). Some syscalls are usingvdso(7)to reduce that overhead. However, for a given syscall, the kernel is doing some work. Depending on the ac...
I receive HTTP request at socket. I want to split HTTP request at header and content. So, I tried this source. ``` //p is char* type, response too p = strtok(response, "\r\n\r\n"); while(NULL != p){ printf("%s\n", p); p = strtok(NULL, "\r\n\r\n"); } ``` Butstrtok()replaced"\r\n"byNULLtoo. I want replace ...
Trystrstr ``` //p1 is char* type, response and p2 too p1 = response; p2 = strstr(response, "\r\n\r\n"); while(NULL != p2){ printf("%.*s\n", p2 - p1, p1); p1 = p2; p2 = strstr(p2 + 1, "\r\n\r\n"); } ```
The C books keep talking about memory blocks, but I never understood what exactly they are. Is a memory block an array? A large memory cell? For example: ``` malloc(2*sizeof(int)); /*This allocates a block*/ ```
A "memory block" is a contiguous chunk of memory. An array in C is also a contiguous chunk of memory. However, using the less-generic term "array" has implications that the generic term "memory block" does not (you can, after all, have data of multiple types within a block, whereas the term "array" implies uniformity...
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 creating program in C which allocates dynamic memory for array and I made function which shows those n...
``` int * data = malloc(count * sizeof(int)); if (data) printf("Allocation succeeded"); else printf("Allocation failed"); ```
If, for instance only 1 thread can access aCritical Sectionat a time, why do we needEventsto synch 2 threads to read/write through it?
There is some overlap in how they can be used, but there are also some unique features to both: Critical sections cannot be used across processes, whereas events can.A single manual-reset event can be used to release multiple threads at once. A critical section cannot.Events are compatible withWaitForSingleObject()et...
In c ~ is 1's complement operator. This is equivalent to: ~a = -b + 1 So, a - ~b -1 = a-(-b + 1) + 1 = a + b – 1 + 1 = a + b Can anyone explains this to me?
From elementary school math we know ``` a = -(-a); ``` From twos complement we know that ``` -a = (~a) + 1 (invert and add one) ``` so we know that ``` a + b = a - (-b) elementary math = a - (~b + 1) twos complement = a - (~b) - 1 distribute the negative (elementary math) ```
I have a program where i need to supply 2 different streams as input. If I only needed one stream as input, I could use stdin like so ``` ./a.out <file1 fgets(buf,1000,stdin) ``` Is it possible to do something like ``` ./a.out --file1 <(cat file1) --file2 <(cat file2) FILE *fp1 = fdopen(3,"r"); FILE *fp2 = fdopen...
If you are using bash as your shell, you can do the following: ``` ./a.out 3< file1 4< file2 ```
About how many clock cycles does it take to make a simple, non-blocking system call on Linux? Would I expect anything different from OS X? I wonder about calls such assetsockopt, which might be used to provide an optional hint to improve performance, yet has its own intrinsic cost.
It really depends on the system call and on the hardware. The overhead of making a syscall is not very big!thisgives less than a microsecond (i.e. a hundred processor clock cycles). Some syscalls are usingvdso(7)to reduce that overhead. However, for a given syscall, the kernel is doing some work. Depending on the ac...
I receive HTTP request at socket. I want to split HTTP request at header and content. So, I tried this source. ``` //p is char* type, response too p = strtok(response, "\r\n\r\n"); while(NULL != p){ printf("%s\n", p); p = strtok(NULL, "\r\n\r\n"); } ``` Butstrtok()replaced"\r\n"byNULLtoo. I want replace ...
Trystrstr ``` //p1 is char* type, response and p2 too p1 = response; p2 = strstr(response, "\r\n\r\n"); while(NULL != p2){ printf("%.*s\n", p2 - p1, p1); p1 = p2; p2 = strstr(p2 + 1, "\r\n\r\n"); } ```
The C books keep talking about memory blocks, but I never understood what exactly they are. Is a memory block an array? A large memory cell? For example: ``` malloc(2*sizeof(int)); /*This allocates a block*/ ```
A "memory block" is a contiguous chunk of memory. An array in C is also a contiguous chunk of memory. However, using the less-generic term "array" has implications that the generic term "memory block" does not (you can, after all, have data of multiple types within a block, whereas the term "array" implies uniformity...
This is probably a really easy question but I can not seem to find an explicit answer online. Say a had a pointer to an array declared as: static char newMessage[400]; char *p = &newMessage; (I don't know if this is right) How would I go about manipulation the newMessage array using only the pointer. I am doing ...
Your code isalmostright; the only problem is that you have mismatched pointer types. You want: ``` char *p = newMessage; ``` Not: ``` char *p = &newMessage; ``` The latter tries to initializep, achar *variable, with a value of typechar (*)[400], which isn't valid C. After you've created and initializedp, you can...
Okay so I understand that a function cannot return an array but rather a pointer to an array but I had other questions. Does the array that I am going to be pointing to need to be declared outside the function? If I dynamically allocate memory for an array in this function, would I able to free it within a function ...
yes you can free the dynamically allocated memory for the array from the calling function. it is fine provided you allocated memory onheapusing function likemalloc(). Then you can free that memory from any function if you have a pointer to that memory usingfree().
After reading a few articles, most of them show how to export C code in Android under JNI. My problem is that I have C++ classes with lots of overloaded functions. If I want to export/wrap them using JNI - Is it possible to do so if I can skip "extern" C which, If I am correct, is used to avoid name mangling of functi...
Removal of name mangling is required any time C code needs to be able to call into C++ code by symbol. If you're unsure if it's safe to turn that off, you can easily find out: assuming you're starting with code that compiles, remove theextern "C"around parts you're interested in. If it still compiles, you're safe... i...
I am trying to create a function which takes in a struct, then adds that struct to the back of a linked List. I have figured out how to add to the front, but i cannot wrap my head around adding to the back. This is my add to front function: ``` MusicRec * addToFront(MusicRec * theList, MusicRec * toBeAdded) { toBeAd...
You need to traverse the list to the end first, then add the new link, something like this: ``` MusicRec *addToBack(MusicRec *theList, MusicRec *toBeAdded) { MusicRec *ptr = theList; if (!ptr) return toBeAdded; while (ptr->next) ptr = ptr->next; ptr->next = toBeAdded; return theList; } ```...
I am not sure about signed hex division by decimal. How canlongtypefff0bdc0divided by1000Lturn to befffffc18? ``` long a = 0xfff0bdc0; a = a/1000L; UARTprintf("a = %x\n", a); ``` result of print : a = fffffc18 Thanks, Jin
Assuming thatlongis a 32-bit integer, and negative numbers are represented using thetwo's complement: ``` fff0bdc0 (hex) = -1000000 (decimal) fffffc18 (hex) = -1000 (decimal) ``` So your result looks correct.
``` int main() { FILE *fp; int testNumber; char answerKey[5]; fp = fopen("test.txt", "r"); for(int i=0; i<4; i++) { fscanf(fp, "%s %d\n", answerKey, &testNumber); printf("%s %d\n", answerKey, testNumber); } return 0; } ``` I am reading from a file that has this in i...
answerKeyis not long enough. To hold 5 chars and a terminating string, it needs to be defined to be an array of at least 6 characters: ``` char answerKey[6]; ```
I am trying to take two elements of an array of integers, and append them, in order, into another array element, but only one. Eg. int i[14] has all elements filled with numbers. I want i[1] and i[2] stored into one element: temp[0]. Say i[1] = 123 and i[2] = 456, I want temp[0] = 123456. I tried using strcat(), b...
No need to use string functions for this, you can do it with math, which is more efficient anyway: ``` temp[0] = pow(10, int(log10(i[2]))) * i[1] + i[2] ``` The idea is to figure out how many decimal places are in i[2] (3 if i[2] is 456), make 10 to that power to get 1000 which is the multiplication factor to then a...
This is probably a really easy question but I can not seem to find an explicit answer online. Say a had a pointer to an array declared as: static char newMessage[400]; char *p = &newMessage; (I don't know if this is right) How would I go about manipulation the newMessage array using only the pointer. I am doing ...
Your code isalmostright; the only problem is that you have mismatched pointer types. You want: ``` char *p = newMessage; ``` Not: ``` char *p = &newMessage; ``` The latter tries to initializep, achar *variable, with a value of typechar (*)[400], which isn't valid C. After you've created and initializedp, you can...
Okay so I understand that a function cannot return an array but rather a pointer to an array but I had other questions. Does the array that I am going to be pointing to need to be declared outside the function? If I dynamically allocate memory for an array in this function, would I able to free it within a function ...
yes you can free the dynamically allocated memory for the array from the calling function. it is fine provided you allocated memory onheapusing function likemalloc(). Then you can free that memory from any function if you have a pointer to that memory usingfree().
After reading a few articles, most of them show how to export C code in Android under JNI. My problem is that I have C++ classes with lots of overloaded functions. If I want to export/wrap them using JNI - Is it possible to do so if I can skip "extern" C which, If I am correct, is used to avoid name mangling of functi...
Removal of name mangling is required any time C code needs to be able to call into C++ code by symbol. If you're unsure if it's safe to turn that off, you can easily find out: assuming you're starting with code that compiles, remove theextern "C"around parts you're interested in. If it still compiles, you're safe... i...
I am trying to create a function which takes in a struct, then adds that struct to the back of a linked List. I have figured out how to add to the front, but i cannot wrap my head around adding to the back. This is my add to front function: ``` MusicRec * addToFront(MusicRec * theList, MusicRec * toBeAdded) { toBeAd...
You need to traverse the list to the end first, then add the new link, something like this: ``` MusicRec *addToBack(MusicRec *theList, MusicRec *toBeAdded) { MusicRec *ptr = theList; if (!ptr) return toBeAdded; while (ptr->next) ptr = ptr->next; ptr->next = toBeAdded; return theList; } ```...
I am not sure about signed hex division by decimal. How canlongtypefff0bdc0divided by1000Lturn to befffffc18? ``` long a = 0xfff0bdc0; a = a/1000L; UARTprintf("a = %x\n", a); ``` result of print : a = fffffc18 Thanks, Jin
Assuming thatlongis a 32-bit integer, and negative numbers are represented using thetwo's complement: ``` fff0bdc0 (hex) = -1000000 (decimal) fffffc18 (hex) = -1000 (decimal) ``` So your result looks correct.
After pressing Ctrl+D, i am expecting this code to print array, but its doing nothing. ``` #include<stdio.h> int main(){ int k,i=0,a; int b[10]; while(scanf("%d",&a)!=EOF){ if(a>(a/4+a/3+a/2)) b[i]=a; else b[i]=(a/4+a/3+a/2); i++; } for(k=0;k<=i;k++){ ...
You're using the wrong key combination to generate an EOF on your operating system (Windows 8).Ctrl+Dis common on unix-like systems, but Windows systems generally useCtrl+Z. Note that you might have to useCtrl+Ztwice if you're not on an empty line (once to flush the current line of input, and once to generate the EOF...
when i run the program i get card.c:3:23: error: dereferencing pointer to incomplete type printf("%i", attacker->power); main.c: ``` #include <stdio.h> #include "card.h" int main(){ return 0; } ``` card.h: ``` #ifndef CARD_H_FILE #define CARD_H_FILE struct card_t { char name[10]; int power, healt...
Unless you made omissions when posting your code,card.cdoesn't includecard.h, which means it knows nothing aboutstruct card_tor its members (->power). It also doesn't inlucdestdio.h, which means it does not know aboutprintf()either. Remember that C compilers translate source (.c) files in isolation, they do not conca...
I would like to check if the firewall is enabled in Windows through C code, I found some methods in C# but only a little bit information from C, How I could do that?, thanks
You could use theWindows Firewall API. For Windows XP you read theInetFwProfile::FirewallEnabledproperty. On Vista or later you could use theWindows Firewall with Advanced Security API.
I make a C program that returns char type value; ``` #include <stdio.h> char *main(){ return "## returned ##"; } ``` I get no message on standard out when I run it. Any good way to see returned value on standard out without driver program?
in C,main()functionalwayshas to return anint.Thatintvalue is returned to the operating system to indicate how did the program exit (successful termination, error during run) etc .... In Windows, the value returned bymain()is stored in a pseudo environment variable namederrorlevel. to check for the its value you can ...
The manual for the standard c library function fseek says: "A successful call to thefseek()function clears the end-of-file indicator for the stream." To me it sounds like saying ifEOF is at 2and I callfseek()to get the pointer at 4, that should work andeofwill be now pointing to 5. But when I test this hypothesis, th...
You have to remember that theEOFflag is not set until you actually try toreadfrom beyond the end of the file. Withfseekclearing the flag, it does this even if you seek to beyond the end of the file. And it works because the flag will be set again next time you read. That is why it's a bad idea to have loops such asw...
This question already has answers here:What does {0} mean when initializing an object?(10 answers)Closed9 years ago. What does {0} mean below? An array of one zero char? But I don't think you can initialize a larger array with a smaller array, or can you? And it would be int, not char, so would cause at least a warn...
{0}means "zero-init" this struct or array. In the example above, rx_buffer.buffer will be filled with all zero bytes instead of whatever happened to be on the stack at that moment. The following should also work for intializing the entire ring_buffer struct to all zero bytes: ``` ring_buffer rx_buffer = {0}; ```
Lets say you have a 5 x 5 array and there are random integers in that array. How would you find the how many 2's there are in the first column? I tried something like this and I got an answer like 222. How can I modify the code for it to just say: there are three 2's in the first coloumn ``` for (i = 0; i<5; ++i) { ...
Add a counter variable to keep track of the count. Increment each time you find a 2, then print it out in the end. Also, if you are only looking at a specific column, you don't need 2 loops. You can just do this: ``` int counter = 0; for (i = 0; i<5; ++i) { if (matrix[i][0]==2) counter++; } printf("%d"...
I'm very confused on how these two functions work with mutex and what they do. Can someone explain them to me and give an example? Thanks!
pthread_cond_signal() -> This is explainhere More explanation : You can do a lots of actions with thread, create, remove, make them stop (lock), make them unlock ... ect pthread_cond_signal() permit to unlock some lock thread. pthread_cond_wait() is used to lock some thread.
In the most tradition way, c/c++ uses.hfor header file extensions. However, in the realworld usage (i.e. Visual C++), there are many other types of header files, such as:.hxx,.hh,.w,.idl, etc. My question is, why people need different types of header files? I don't have a complete list of all the header types I saw, ...
For the compiler there's no difference. You can use the extension that you want, or even no extension at all. So,.hh,.hxx,.my_awesome_extensionare valid. The only important thing for the compiler is that it can find a file with the name you specify.
I want to castinttochar. This is my code. ``` #include <stdio.h> int main(){ int i = 7; char *s; sprintf(s,"sprint f = %d",i); printf("printf s = [%s]",s); } ``` It endsSegmentation fault. What’s wrong is it?
You do not have any memory allocated fors. It's just a pointer that is either NULL or pointing to a random location (depending on the compiler). Trying to write to it is like going to bed without caring where you are - and the probability that you've just broken into someone else's house is way larger than randomly se...
I encountered code where: ``` typedef wchar_t str_param_t[WP_STR_MAX_LEN]; ``` And then: ``` typedef struct work_t { u32_t val1; u32_t val2; str_param_t data[WP_MAX_COUNT_STR]; } work_t; ``` My question is what type isdata?
It is an array of lengthWP_MAX_COUNT_STRcontainingwchar_t-based strings of lengthWP_STR_MAX_LENeach.
This question already has answers here:Is it possible to call a C function from C#.Net(5 answers)Closed9 years ago. I have to call my c method from c# coding.I have included .c file in our project.In c file i have test() method.I don't know how to call in c#. I don't want to convert my c project to dll file.
I don't want to convert my c project to dll file. You might not want to do that, but it's the only way. The most common solutions to your problem are: Compile C code into unmanaged DLL and call it using p/invoke.Compile C code into a COM server and use COM interop.Wrap the C code in a C++/CLI mixed mode assembly whi...
I encountered code where: ``` typedef wchar_t str_param_t[WP_STR_MAX_LEN]; ``` And then: ``` typedef struct work_t { u32_t val1; u32_t val2; str_param_t data[WP_MAX_COUNT_STR]; } work_t; ``` My question is what type isdata?
It is an array of lengthWP_MAX_COUNT_STRcontainingwchar_t-based strings of lengthWP_STR_MAX_LENeach.
This question already has answers here:Is it possible to call a C function from C#.Net(5 answers)Closed9 years ago. I have to call my c method from c# coding.I have included .c file in our project.In c file i have test() method.I don't know how to call in c#. I don't want to convert my c project to dll file.
I don't want to convert my c project to dll file. You might not want to do that, but it's the only way. The most common solutions to your problem are: Compile C code into unmanaged DLL and call it using p/invoke.Compile C code into a COM server and use COM interop.Wrap the C code in a C++/CLI mixed mode assembly whi...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question appears to be off-topic becauseit lacks sufficient information to diagnose the problem.Describe your problem in more detail orinclude a minimal examplein the question itself.Closed9 years ago.Improve this q...
If running Linux, You can catch the SIGINT signal and flush all your data into the file in the signal handler. Normally all processes in Linux receive SIGINT with default signal mask. All you have to do is to write signal handler function and then use sigaction() system call. http://man7.org/linux/man-pages/man2/siga...
I am a little bit surprised the following code does not compile. Can you shed some light on it? (header file) ``` enum CarType_e { CAR_BMW = 0, CAR_KIA, CAR_HONDA, CAR_FORD, CAR_MERCEDES }; int build_car(CarType_e type); ``` and then I get the following error: ``` In file included from car.c:19...
You have two choices, use ``` typedef enum { CAR_BMW = 0, CAR_KIA, CAR_HONDA, CAR_FORD, CAR_MERCEDES } CarType_e; ``` Or, you can use - ``` int build_car(enum CarType_e type); ``` I tested both with gcc on linux.
In C, if I put a literal string like"Hello World \n\t\x90\x53"into my code, the compiler will parse the escape sequences into the correct bytes and leave the rest of characters alone. If the above string is instead supplied by the user, either on the command line or in a file, is there a way to invoke the compiler's ...
No, there's no standard function to do that. A suggestion for a non-standard library solution is to useglib'sg_strcompress()function.
Withfloat a = ...;andfloat inva = 1/a;isx / athe same asx * inva? And what is with this case: ``` unsigned i = ...; float v1 = static_cast<float>(i) / 4294967295.0f; float scl = 1.0f / 4294967295.0f; float v2 = static_cast<float>(i) * scl; ``` Isv1equal tov2for all unsigned integers?
isv1equal tov2for all unsigned integers? Yes, because4294967295.0fis a power of two. Division and multiplication by the reciprocal are equivalent when the divisor is a power of two (assuming the computation of the reciprocal does not overflow or underflow to zero). Division and multiplication by the reciprocal are n...
I'm developing a script that checks the version of some installed C programs. The version check is performed with the --version option. However, this option may not be implemented in all the checked programs. When the option is implemented I use: ``` version=$(./$program_name --version) ``` But when it's not, the pr...
Not completely waterproof but I nice start is using strings: ``` strings /usr/bin/git | grep -- --version ```
I have made this little code: ``` void *toto = malloc(8 * sizeof(char *) * 8); char **tata = (char **)toto; tata[5][5] = 'a' ``` But I have asegmentation fault. How can I convert myvoid *to achar **?
Themalloccall is allocating space for 64 pointers ofuninitializedmemory. Then, you are usingtataas a double indirection pointer. That's it: tatapoints to the start of the 64 pointers.tata[5]is the sixth element of themallocd block, and sincetatahas typechar**,tata[5]has typechar*: a pointer with garbage.tata[5][5]is ...
I've just compiled this C program using Cygwin's gcc: ``` #include <stdio.h> void main (){ char *str; gets(str); printf("%s",str); } ``` Setting asidegetsisdeprecatedgone, this is supposed to break since I'm not allocating any memory for str, but it works even with very long inputs. If, for example, I s...
Access memory region pointed to by uninitialized pointer isundefined behavior, it could crash, it also could look like working normally. In a word, you cannot predict its behavior. How come I'm not getting a segmentation fault? Uninitialized pointer has an undetermined value, it could point to anywhere, if it points...
When I try to compile this: ``` #include <SDL/SDL.h> #include "SDL_thread.h" int main(void) { SDL_Thread athread; return 0; } ``` with: ``` gcc SDL_Thread_test.c -o SDL_Thread_test `sdl2-config --cflags --libs` -lSDL ``` I get: ``` error: storage size of ‘athread’ isn’t known SDL_Thread athread; ...
You cannot create a SDL_thread structure. The structure information is private and not known to the compiler. SDL_Thread API only requires you to use a pointer to SDL_Thread which you can declare. ``` SDL_Thread* thread ; //note the pointer thread = SDL_CreateThread(int (*fn)(void *), void *data); ``` You will n...
I have a C program which takes a file as an argument, cleans up the file and writes the cleansed data to a new temp file. It then accepts some stdin, cleans it up and sends it stdout. I have a second file which performs operations on this temp file and on the stdin again. ``` ./file_cleanse <file1.txt> | ./file_oper...
What about: ``` ./file_cleanse <file1.txt> > /tmp/temporaryFile ./file_operation <temp.txt> < /tmp/temporaryFile ```
I have a piece of code to do execvp. ``` if (0 != child_pid) { /* Parent Process */ printf("This is parent process: PID: %d\n",getpid()); return child_pid; } else { /* Child Process */ printf("This is child process: PID: %d\n",getpid()); printf("Parent process is: PPID: %d\n",getppid()); e...
/proconly contains entries for processes that currently exist. It sounds like your process has terminated and no longer exists by the time you go looking for it in/proc.
I'm making a program that read CSV files based on the arguments of the C program called read-log example ``` $ ./read-log file1.csv $ ./read-log file1.csv file2.csv nofile.csv ``` But I also need my program to read files when using the unix commandcatbut when I input: ``` $ cat file1.csv |./read-log ``` The prog...
Just use theFILE *stdinthat is open by default: ``` FILE *fp; if (argc > 1) { if (strcmp(argv[1], "-") == 0) // Many utilities accept "-" for the fp = stdin; // filename to indicate stdin else fp = fopen(argv[1], "r"); } else { fp = stdin; } ``` When you're done us...
I would like to write a struct into a binary file. My struct looks like this: ``` struct { int a; int b; struct c { int d; int e; }; }; ``` is there any function, to write an instance of this structure into a file? If not, then how should I do it?
There's no automated way in C to read/write structures to a file. You're going to have to create your own formatting and parsing routines. Basically calls to sprintf/write and read/sscanf with the appropriate formatting strings. If you can switch to C++ then check out JSON or XML libraries. The technical term for sav...
So, I'm getting an error on this line of code; ``` else if(lockError == EBUSY) ``` I get the error; ``` use of undeclared identifier 'EBUSY' ``` How do I compare my int lockError to the EBUSY that might be returned when I try a pthread_mutex_unlock.
You forgot to include#include<errno.h>whereEBSUYis defined. Seeerrno.h.
I have a function that has an argument 'char *argument', like: ``` function(char *x) { ... } ``` When I call this function, I pass a char array as the argument ``` function(char_array); ``` In the function, I want to iterate the elements of the array char by char, so my thought was creating an array in the functio...
You can't. But what you can do is iteratexdirectly as pointers can be used like arrays just as arrays can be converted to pointers. E.g. ``` function(char *x) { for(int i = 0; i < 100; i++) printf("%d ", x[i]); } ```
I noticed that when I compile thisiniparserit spits the following warning: ``` src/iniparser.c:244:5: warning: implicit declaration of function ‘snprintf’ [-Wimplicit-function-declaration] snprintf(keym, secsize, "%s:", s); ``` The solution was supposedly to add: ``` #include <stdio.h> ``` I tried this, but t...
snprintfis specified only in C99, unlikesprintfwhich is in C90. Seeman sprintffor more information.
I'm using the SWIG library to let a Java (Android) app call C functions. I need to have some of my C functions return variable-sized arrays back to Java. How can I do this? I've considered converting a long long * to a jlongarray, but I don't know how to pass the jlongarray back to Java with SWIG. Does anyone know ...
I tried to make a custom typemap in SWIG, but I got segfaults when I did that. I eventually solved the problem by writing a new function in straight JNI that puts the array elements into a jlongArray, rather than letting SWIG write a wrapper function for it.
Going down the rabbit hole of variadic macros in glibc, I’ve reached/usr/lib/gcc/x86_64-linux-gnu/4.8.2/include/stdarg.hwhere, for example, theva_startmacro is defined as: #define va_start(v,l) __builtin_va_start(v,l) But I’ve been trying to look for the actual implementation of__builtin_va_start(v,l)without succes...
To look in the source code of gcc, download the matching version fromhttp://www.netgull.com/gcc/releases/For example, the 4.8.2 version is athttp://www.netgull.com/gcc/releases/gcc-4.8.2/(82 MB). The builtin keyword is handled at line 4169 ofgcc/builtins.c
I've just compiled this C program using Cygwin's gcc: ``` #include <stdio.h> void main (){ char *str; gets(str); printf("%s",str); } ``` Setting asidegetsisdeprecatedgone, this is supposed to break since I'm not allocating any memory for str, but it works even with very long inputs. If, for example, I s...
Access memory region pointed to by uninitialized pointer isundefined behavior, it could crash, it also could look like working normally. In a word, you cannot predict its behavior. How come I'm not getting a segmentation fault? Uninitialized pointer has an undetermined value, it could point to anywhere, if it points...
When I try to compile this: ``` #include <SDL/SDL.h> #include "SDL_thread.h" int main(void) { SDL_Thread athread; return 0; } ``` with: ``` gcc SDL_Thread_test.c -o SDL_Thread_test `sdl2-config --cflags --libs` -lSDL ``` I get: ``` error: storage size of ‘athread’ isn’t known SDL_Thread athread; ...
You cannot create a SDL_thread structure. The structure information is private and not known to the compiler. SDL_Thread API only requires you to use a pointer to SDL_Thread which you can declare. ``` SDL_Thread* thread ; //note the pointer thread = SDL_CreateThread(int (*fn)(void *), void *data); ``` You will n...
I have a C program which takes a file as an argument, cleans up the file and writes the cleansed data to a new temp file. It then accepts some stdin, cleans it up and sends it stdout. I have a second file which performs operations on this temp file and on the stdin again. ``` ./file_cleanse <file1.txt> | ./file_oper...
What about: ``` ./file_cleanse <file1.txt> > /tmp/temporaryFile ./file_operation <temp.txt> < /tmp/temporaryFile ```
I have a piece of code to do execvp. ``` if (0 != child_pid) { /* Parent Process */ printf("This is parent process: PID: %d\n",getpid()); return child_pid; } else { /* Child Process */ printf("This is child process: PID: %d\n",getpid()); printf("Parent process is: PPID: %d\n",getppid()); e...
/proconly contains entries for processes that currently exist. It sounds like your process has terminated and no longer exists by the time you go looking for it in/proc.
I'm making a program that read CSV files based on the arguments of the C program called read-log example ``` $ ./read-log file1.csv $ ./read-log file1.csv file2.csv nofile.csv ``` But I also need my program to read files when using the unix commandcatbut when I input: ``` $ cat file1.csv |./read-log ``` The prog...
Just use theFILE *stdinthat is open by default: ``` FILE *fp; if (argc > 1) { if (strcmp(argv[1], "-") == 0) // Many utilities accept "-" for the fp = stdin; // filename to indicate stdin else fp = fopen(argv[1], "r"); } else { fp = stdin; } ``` When you're done us...
I would like to write a struct into a binary file. My struct looks like this: ``` struct { int a; int b; struct c { int d; int e; }; }; ``` is there any function, to write an instance of this structure into a file? If not, then how should I do it?
There's no automated way in C to read/write structures to a file. You're going to have to create your own formatting and parsing routines. Basically calls to sprintf/write and read/sscanf with the appropriate formatting strings. If you can switch to C++ then check out JSON or XML libraries. The technical term for sav...
So, I'm getting an error on this line of code; ``` else if(lockError == EBUSY) ``` I get the error; ``` use of undeclared identifier 'EBUSY' ``` How do I compare my int lockError to the EBUSY that might be returned when I try a pthread_mutex_unlock.
You forgot to include#include<errno.h>whereEBSUYis defined. Seeerrno.h.
I have a function that has an argument 'char *argument', like: ``` function(char *x) { ... } ``` When I call this function, I pass a char array as the argument ``` function(char_array); ``` In the function, I want to iterate the elements of the array char by char, so my thought was creating an array in the functio...
You can't. But what you can do is iteratexdirectly as pointers can be used like arrays just as arrays can be converted to pointers. E.g. ``` function(char *x) { for(int i = 0; i < 100; i++) printf("%d ", x[i]); } ```
I noticed that when I compile thisiniparserit spits the following warning: ``` src/iniparser.c:244:5: warning: implicit declaration of function ‘snprintf’ [-Wimplicit-function-declaration] snprintf(keym, secsize, "%s:", s); ``` The solution was supposedly to add: ``` #include <stdio.h> ``` I tried this, but t...
snprintfis specified only in C99, unlikesprintfwhich is in C90. Seeman sprintffor more information.
I'm using the SWIG library to let a Java (Android) app call C functions. I need to have some of my C functions return variable-sized arrays back to Java. How can I do this? I've considered converting a long long * to a jlongarray, but I don't know how to pass the jlongarray back to Java with SWIG. Does anyone know ...
I tried to make a custom typemap in SWIG, but I got segfaults when I did that. I eventually solved the problem by writing a new function in straight JNI that puts the array elements into a jlongArray, rather than letting SWIG write a wrapper function for it.
Going down the rabbit hole of variadic macros in glibc, I’ve reached/usr/lib/gcc/x86_64-linux-gnu/4.8.2/include/stdarg.hwhere, for example, theva_startmacro is defined as: #define va_start(v,l) __builtin_va_start(v,l) But I’ve been trying to look for the actual implementation of__builtin_va_start(v,l)without succes...
To look in the source code of gcc, download the matching version fromhttp://www.netgull.com/gcc/releases/For example, the 4.8.2 version is athttp://www.netgull.com/gcc/releases/gcc-4.8.2/(82 MB). The builtin keyword is handled at line 4169 ofgcc/builtins.c
I have a simple program to calculate the volume of a cube. It runs fine, but the result I get is wrong. It comes out as "Y is 392". Can anyone help me understand why it is 392? I have just begun C, so I do not understand all of the code. I realise this Macro is badly written, I am just trying to understand its behavi...
This is because the macro expands to: ``` y = ++x * ++x * ++x; ``` This is a very badly written macro, for this very reason; it looks like a function call (which would evaluate the argument only once) but it really evaluates it three times. This gives undefined behavior since there is a lack ofsequence points.
Well I think I know the answer to the question but I rather be assured. If you malloc memory on the heap and exit the program before you free the space does the os or compiler free the space for you ?
The OS free the space for you when it removes the process's descriptor (task_structin Linux's case) from its process list. The compiler usually generates anexit()system call and there's where all this is handled. On Linux, basically, all these happens in the kernel'sexit_mm()function, eventually invoked byexit(). It...
I would like to return the height of the iPhone status bar from a c/c++ function. I did this in an mm file: ``` int ios_status_bar_height_platform() { return [UIApplication sharedApplication].statusBarFrame.size.height; } ``` It claims that it doesn't know what UIApplication is. How do I include and how do I k...
At the top of theUIApplication Class Referenceyou'll find Framework: /System/Library/Frameworks/UIKit.framework therefore ``` #import <UIKit/UIKit.h> ``` should help. For more information, see"Including Frameworks in Your Project"in the "Framework Programming Guide".
I'm trying to use my project file in c, but it wont let me do it, it gives invalid configuration file then shows the directory of my project file. I am using Turbo C simulator for windows 7 64 bit I already tried to re install it but same error keeps happening, i can run normal files though just cant include my proj...
Do yourself a favor and install some worthy compiler. There are alot of options available on the market. I preferMicrosoft Visual Studio. Some free worthy compilers: Microsoft Visual StudioExpressCode BlocksEclipse
Here is a part of the code: ``` #define GPIO_PORTF_DATA_BITS_R ((volatile unsigned long *)0x40025000) #define LED_BLUE 0x04 #define LED_GREEN 0x08 #define LED_RED 0x02 GPIO_PORTF_DATA_BITS_R[LED_BLUE | LED_GREEN | LED_RED] = (LED_GREEN | LED_RED) ``` With my the little understanding I have about pointers, it is eq...
In C, the indexing operator[]has the following semantics:a[b]means*(a + b), so eitheraorbmust evaluate to an address. Thus, your example means*(0x40025400 + 0xe) = 0xa, i.e. it accesses a register which is at offset 0xe *sizeof (unsigned long)from the base address at 0x40025400. The scaling is since the pointer is to...
I have a file hello.c (no hello.o yet).When I give command ``` gcc -o hello hello.o ``` It gives errorgcc: error: hello.o: No such file or directory, but when I create a makefile containing following rule, ``` hello: hello.o gcc -o hello hello.o ``` and runmake, it automatically createshello.ofromhello.cand th...
makehas not only uses the rules you added explicitly in makefiles, it has implicit rules as well. The full list you can find athttps://www.gnu.org/software/make/manual/html_node/Catalogue-of-Rules.html#Catalogue-of-Rulesand the first implicit rule in the list is Compiling C programsn.o is made automatically from n.c ...
(Edited change C/C++ to C) Please help me to find out a clean clarification oncharandunsigned charin C. Specially when we transfer data between embedded devices and general PCs (The difference between buffer ofunsigned charand plainchar).
You're asking about two different languages but, in this respect, the answer is (more or less) the same for both. You really should decide which language you're using though. Differences: they are distinct typesit's implementation-defined whethercharis signed or unsigned Similarities: they are both integer typesth...
I am new to open CV and C. How do i specify multiple images for the same kind of operation.
if your images are (sequentially) numbered, you could abuse a hidden feature with VideoCapture, just pass it a (format) string: ``` VideoCapture cap("/my/folder/p%05d.jpg"); // would work with: "/my/folder/p00013.jpg", etc while( cap.isOpened() ) { Mat img; cap.read(img); // process(img); } ```
i have another question. Can i set an array as [fixed][dynamic]?, the first value will be reader from a file ( numbers of sensors used by user ) and the other value will be a dynamic array [time of reading]. I was reading about 2D dynamic arrays, but i do not know if i can do this. Any advise?. Thanks.
Sure you can... Just declare an array of pointers. Then you can usemallocandreallocto modify the subarray stored at each element. ``` struct reading * data[num_sensors]; ``` But you're kinda talking aboutboththe dimensions being dynamic. You might need: ``` struct reading ** data = malloc(sizeof(struct reading*)...
I have this c code that have a global variable main_prog.c ``` PLD po; int main(){} ``` i have this function in the definition functiondef.c ``` void function(PLD po) { extern po; } ``` what my problem is that how do the compiler know that it is using the extern po or the parameter po??
You can definitely access the extern variable if you declare it in a different scope. ``` void function(PLD po) { { extern PLD po; //this is the po declared in main } } ```
I have a struct and an dynamic array inside the struct. I want to malloc this array but i don't really now how. I want that array void because i want the members of this array to be structs. As you can see i tried something but it doesn't really work ``` #include <stdio.h> #include <stdlib.h> #include <string.h> str...
exp1 isn't a pointer. Use ``` exp1.stack = malloc(n); ```