question
stringlengths
25
894
answer
stringlengths
4
863
I am using printf via assembly code. I note that in the following example if I ommit the expected argument, garbage is printed. ``` .386 .model flat, c .stack 100h printf PROTO arg1:Ptr Byte, printlist:VARARG .data msg3fmt byte 0Ah,"%s",0Ah,"test output",0Ah,0 .code main proc INVOKE printf, ADDR m...
The reason is that the format specifiers tell printf how many arguments it should have received. Printf gets its data from the stack; if you don't provide any data for it then it will pull whatever happened to be on the stack and treat as an argument.
Is it possible to place a linked list index before the output of result in opencv? For example, I have code ``` for( ; i!= 0; i= i->h_next ) { printf("Index number = %d Area = %.2f \n",n, area); } ``` Now, my question is, how to print this index number? As the values ofiare not in 1,2,3 and so on..
Maybe try: ``` int cnt = 0; for ( .. ) { printf("%d\n", cnt++); } ```
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...
Postgres supports those features.
I tried to copy files with curl after the following example: ``` CURL *curl; FILE *fp; CURLcode res; char *url = "http://localhost/aaa.txt"; char outfilename[FILENAME_MAX] = "D:\\bbb.txt"; curl = curl_easy_init(); if(curl) { fp = fopen(outfilename,"wb"); curl_easy_setopt(curl, CURLOPT_URL, url); curl_ea...
You miss a call tocurl_easy_perform. See theAPI descriptionof it.
I found the following snippet (I think in Wikipedia) that creates a different run-time when C++ comments are recognized than when not: ``` int a = 4 //* This is a comment, but where does it end? */ 2 ; ``` But until now that's been the only one (variants excluded). I'm not interested in differentiating using__STD...
This program will print0.000000on a conforming C89 implementation and1.000000on a conforming C99 implementation: ``` #include <stdio.h> #include <stdlib.h> int main() { double d = strtod("0x1", NULL); printf("%f\n", d); return 0; } ```
I simply write this: ``` char* test="test"; printf("%s",test[0]); ``` it says seg fault; then I change toprintf("%s",&test[0]);the error gone But this is not what I want; the console print: "test " how to get just value "t" from that pointer?
If you want just thet, you should do: ``` printf("%c",test[0]); ``` The format%c, will print a singlechar. %swill print the entire null-terminated string.
Libcurl uses the following to define the email recipient: ``` #define RECIPIENT "<bla@bla.com>" ``` But what if I don't want to hard code the recipient? I want a user to be able to supply his/her own email address, so I need to find a way to do this: ``` std::string emailreceiver = "bla@bla.com"; #define RECIPIENT ...
Curl expects a C string (const char *), not a C++ string (std::string). So try: ``` std::string emailreceiver = "bla@bla.com"; rcpt_list = curl_slist_append(rcpt_list, emailreceiver.c_str()); ``` There's no need to use a#defineat all, that was just an example.
Is there any recommendations for how to show what your code is doing (C or MATLAB)? Imagine if your code is really long and you have a lot of functions in your program, what is the best way to document the program? I know Java IDEs have a way to ingest comments and spit them back out into a document that shows all t...
What Java uses isJavaDoc. For C, you can useDoxygen. I also sawthiswhich suggests you can use Doxygen with matlab too!
I'm writing a GTK based chat and want to implement the following: In a GtkTextView when hitting Enter a message is sent, but hitting Shift+Enter types a new line. I just can't figure out how to detect the multiple key press. I can detect just one key with GdkEventKey.
Peek inside the state member of e GdkEventKey , it holds abitmaskof which of modifier keys (shift/control/alt and others) that are also pressed. In the general case of detecting several keys being pressed, you have to keep track of the pressed keys yourself, i.e. on a key pressed event, you remember that the key is p...
I want to convert number from char * format to 32 bit integer int32_t, but strtol() returns long. I don't know length of long on my machine. It could be 32 or 64 bit or something else in the future. What is the correct and bulletproof way to convert string to 32 bit integer int32_t? Or to convert long to int32_t. I...
Usesscanfwith one of the format specifier macros from<inttypes.h>, e.g.SCNd32orSCNi32: ``` int32_t i; sscanf(str, "%"SCNd32, &i); ``` These are available since C99.
scala can make mapping (ADT) so we can mapping like this ('A', 3) = (Char, Int) how about in C? I want to mapping and check all the relations and comparing between two maps 'a' = 1, 'b' = 3, 'c' = 4 is mapping by abbbcccc and 'e' = 1 , 'b' = 3, 'g' = 4 is mapping by bbbegggg I want to find these relation ('a' , 1...
Not in plain C, no. You could implement one with an array or two, but you would have to implement either a hashing algorithm, or some kind of comparison and search algorithm. Alternatively you could use some kind of search tree to implement it. If you don't want to write a map data type, you will have to use a libra...
Suppose I have a pointer to image data which has 3 channels (RGB), 8 bits per channel and I want to display the value of a pixel like #000000, which is a 24 bit number. The data is stored like RGB RGB RGB ... so I really need to read the first three bytes. ``` typedef unsigned char uchar; uchar* data = get_image_data...
You can bit-shift right by 8 bits to achive this. ``` uint32_t value = *((uint32_t*) data) >> 8; printf("Value is %0X", value); ``` Example wheredatais two pixels of value#1177ff: ``` data = 11 77 ff 11 77 ff value = 11 77 ff 11 value >> 8 = 00 11 77 ff ```
I have found the contours using cvfindcontour, and, now I want to access first and second contour and find the euclidean distance between them. Could anybody help me with its code? ``` CvPoint *contourPoint, *contourPoint2; contourPoint = (CvPoint *)CV_GET_SEQ_ELEM(CvPoint,contours,1); contourPoint2 = (CvPoint *)CV_G...
I would usecvMomentsto compute the centroid of each contour, and then compute theEuclidean distancebetween the two centroids.Hereis a post on openframeworks about it.Hereis a post from the opencv mailing-list. Hope that helps!
I have a number for example:2.4444444. I need to get first digit after the dot -- in my case it's4. How to implement it?
How about ``` ( (int)(floor( fabs( num ) * 10 ) ) ) % 10 ```
I am using printf via assembly code. I note that in the following example if I ommit the expected argument, garbage is printed. ``` .386 .model flat, c .stack 100h printf PROTO arg1:Ptr Byte, printlist:VARARG .data msg3fmt byte 0Ah,"%s",0Ah,"test output",0Ah,0 .code main proc INVOKE printf, ADDR m...
The reason is that the format specifiers tell printf how many arguments it should have received. Printf gets its data from the stack; if you don't provide any data for it then it will pull whatever happened to be on the stack and treat as an argument.
Is it possible to place a linked list index before the output of result in opencv? For example, I have code ``` for( ; i!= 0; i= i->h_next ) { printf("Index number = %d Area = %.2f \n",n, area); } ``` Now, my question is, how to print this index number? As the values ofiare not in 1,2,3 and so on..
Maybe try: ``` int cnt = 0; for ( .. ) { printf("%d\n", cnt++); } ```
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...
Postgres supports those features.
I tried to copy files with curl after the following example: ``` CURL *curl; FILE *fp; CURLcode res; char *url = "http://localhost/aaa.txt"; char outfilename[FILENAME_MAX] = "D:\\bbb.txt"; curl = curl_easy_init(); if(curl) { fp = fopen(outfilename,"wb"); curl_easy_setopt(curl, CURLOPT_URL, url); curl_ea...
You miss a call tocurl_easy_perform. See theAPI descriptionof it.
I found the following snippet (I think in Wikipedia) that creates a different run-time when C++ comments are recognized than when not: ``` int a = 4 //* This is a comment, but where does it end? */ 2 ; ``` But until now that's been the only one (variants excluded). I'm not interested in differentiating using__STD...
This program will print0.000000on a conforming C89 implementation and1.000000on a conforming C99 implementation: ``` #include <stdio.h> #include <stdlib.h> int main() { double d = strtod("0x1", NULL); printf("%f\n", d); return 0; } ```
I simply write this: ``` char* test="test"; printf("%s",test[0]); ``` it says seg fault; then I change toprintf("%s",&test[0]);the error gone But this is not what I want; the console print: "test " how to get just value "t" from that pointer?
If you want just thet, you should do: ``` printf("%c",test[0]); ``` The format%c, will print a singlechar. %swill print the entire null-terminated string.
Libcurl uses the following to define the email recipient: ``` #define RECIPIENT "<bla@bla.com>" ``` But what if I don't want to hard code the recipient? I want a user to be able to supply his/her own email address, so I need to find a way to do this: ``` std::string emailreceiver = "bla@bla.com"; #define RECIPIENT ...
Curl expects a C string (const char *), not a C++ string (std::string). So try: ``` std::string emailreceiver = "bla@bla.com"; rcpt_list = curl_slist_append(rcpt_list, emailreceiver.c_str()); ``` There's no need to use a#defineat all, that was just an example.
Is there any recommendations for how to show what your code is doing (C or MATLAB)? Imagine if your code is really long and you have a lot of functions in your program, what is the best way to document the program? I know Java IDEs have a way to ingest comments and spit them back out into a document that shows all t...
What Java uses isJavaDoc. For C, you can useDoxygen. I also sawthiswhich suggests you can use Doxygen with matlab too!
I just ran into this piece of code that does this : ``` delete a, a = 0; ``` It compiles and runs just fine. But isn't this supposed to be : ``` delete a; a = 0; ``` Why is separating statements using , allowed in this case ? Thanks :)
In C and C++, most "statements" are actually expressions. The semicolon added to an expression makes it into a statement. Alternatively, it is allowed (but almost always bad style) to separate side-effectful expressions with the comma operator: the left-hand-side expression is evaluated for its side-effects (and its...
Look at this code ``` h = (c >> 4) & 0xf; l = c & 0xf; printf(h + 'x'); ``` How do I convert this code to C#?
That printf is completely wrong, you are attempting to make a pointer from an integer without a cast and surely you don't want to cast the number to a const char*. Assuming it is meant to print the assumed unsigned integer. The equivalent is: ``` System.Console.WriteLine(120 + (c / 16)); ``` or to be pedantic: ``` ...
I'm importing a C project to Eclipse CDT which has a preinclude header file. I want to know if there's an option to preinclude the file in the projects settings, The projects doesn't compile because of unresolved defines, that needs to be defined in the start. does anyone encountered this before ?
Yes, I've seen such problems several times. If your project doesn't compile, you'll have to change the compiler options, since the compiler needs to know about the file. It depends on your compiler, though, since this is not a C feature.
I wanted to read input from user (multiple lines) and write it into a file using fputs(). Here is my code ``` #include<stdio.h> #include<stdlib.h> int main() { FILE *fp; char s[25]; fp=fopen("myname","w"); if(fp==NULL) { perror("Error opening file\n"); exit(1); } while(fgets(s,25,stdin)!=NULL) fputs(s,...
SinceC-Clikely kills the process, because of buffering, the lines won't get to the file (unless there's a lot of them and they fill the buffer). You should end the output withC-D(Unix) orC-Z(Dos), notC-C. As a side note:fgetsdoesn't strip the newline andfputsadds its own. But I guess you were going to notice that :-...
I am using Visual studio in windows for developing C library. Can someone please provide me simple example of creating thread in windows console application and starting it. Thanks
C++ and C doesn't have support for Threads. You have to use Win32 APIs for threading support for which you can google,BING.
I have a program which does concatenation. its like char *testConc(int a,..) Where a indicates number of arguments are being passed for concatenation. As legth keeps on changing is there is anything like constructor overloading in C or any simple syntax which implements the functionality
Yes, there arevaradic functions ``` #include <stdio.h> #include <stdarg.h> /* print all non-negative args one at a time; all args are assumed to be of int type */ void printargs(int arg1, ...) { va_list ap; int i; va_start(ap, arg1); for (i = arg1; i >= 0; i = va_arg(ap, int)) printf("%d ", i); va...
How can I format string to ensure that it is shown as: ``` ID:12 SIZE:235235235235 ID:1455 SIZE:335235 ``` Instead of: ``` ID:12 SIZE:235235235235 ID:1455 SIZE:335235 ``` Tabs do NOT work in all cases, they only help with this if the length variance is +/- 4-5 characters. Is th...
When you print something withprintf, you can specify a field width; the value is justified in the field. For example: ``` printf("ID: %5d SIZE: %10d", id, size); ``` will right-justify the id in a 5-character field, and the size in a 10-character field.
So this is pretty basic, but I don't really know C. I want to find the number of milliseconds something takes to run, not clock (CPU) cycles. I tried using ``` struct timeval start,end; double dif; gettimeofday(&start, 0); //do stuff gettimeofday(&end, 0); dif = (end - start) / 1000.0; printf("The time taken was %...
Change ``` dif = (end - start) * 1000; ``` to ``` dif = (end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000; ``` In pseudocode: ``` Get the seconds part of the time delta Multiply by 1000 to get milliseconds Get the microseconds part of the time delta Divide that part by 1000 Add that part ...
The MPI spec dictates to callMPI_Finalizein each thread before exiting. How does that work with runtime errors like assertions? If Iassert(cond)andcondevaluates to false, I have no chance to callMPI_Finalizebecause the normal program flow is changed. Am I supposed to catchSIGABRT,SIGSEGVand god-knows-what-else myself...
Write your own version of assert that calls MPI_Finalize after asserting. ``` #define MY_ASSERT(cond) do { \ if (!cond) { \ printf ("Assert (%s) failed at %s:%d\n", #cond, __FILE__, __LINE__); \ MPI_finalize (); \ } \ } while (0); ``` Note that in any case the other MPI processes in your job ...
Can someone explain to me the difference between: int *arr[5]vs.int (*arr)[5]vs.int *(*arr)[5] I'm trying to wrap my mind around how pointers/arrays are actually represented in C...
I would suggest usinghttp://cdecl.org. int *arr[5]"declare arr as array 5 of pointer to int"int (*arr)[5]"declare arr as pointer to array 5 of int"int *(*arr)[5]"declare arr as pointer to array 5 of pointer to int" plus a visit to this page from MSDN:Interpreting more complex declarators.
``` system(do_this); // which executes an external program to output a phrase on the screen printf("=My taxes"); ``` Output: 500$=My taxes Expected output: 500$=My taxes I don't have control over the code executing indo_thiswhich automatically outputs the'\n'.
This should work: ``` system("program | tr -d '\012\015'"); printf("=My taxes\n"); ``` whereprogramis the program you want to run. Thetrcommand removes all CR and LF characters (codes 015 and 012 octal) fromprogram's output. The solution assumesprogramonly outputs one line (your tax) and it works on systems with lin...
I know I can run "ulimit -c unlimited" In the shell to turn on core dumps for the current user. What I am wondering is how can I do this programmatically from C? I see there is a ulimit call, but it's been deprecated in favour of get/setrlimit. What I want to know is what is the equivalent call to setrlimit that wo...
I found a working solution. The core files are now being created. ``` struct rlimit core_limit; core_limit.rlim_cur = RLIM_INFINITY; core_limit.rlim_max = RLIM_INFINITY; if (setrlimit(RLIMIT_CORE, &core_limit) < 0) fprintf(stderr, "setrlimit: %s\nWarning: core dumps may be truncated or non-existant\n", strerror...
I need help with a simplecstructure and can't find it why it's not compiling usinggcc(opensuse 11.4) I have this code: ``` struct Image { int w; int h; // other code }; ``` in the same file I have another struct array like this: ``` struct ShapeImage { Image image[10]; // other code }; ``` when I compile I...
It should be: ``` struct Image image[10] ; ``` Or use typedef while defining the struct: ``` typedef struct { int w; int h; // other code } Image; ``` And use the code otherwise same as in your question.
GCC has a statment expression feature that allows macro to be defined as: ``` #define maxint(a,b) \ ({int _a = (a), _b = (b); _a > _b ? _a : _b; }) ``` This is illegal in Visual Studio. Is there an equivalent feature in microsoft visual studio? (I know, I would better use GCC. But I am just curious). Or, do we ...
There is no equivalent in the MS compiler to this non-standard GCC language extension.
In linux,container_ofmacro is enclosed in seemingly "extra" parentheses: ``` #define container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); (type *)( (char *)__mptr - offsetof(type,member) );}) ``` Instead of it, can we just use ``` #define contain...
It's necessary. One of the "tricks" used is GCC'sstatement expressionsthat require this 'strange'({ code })syntax. Code that uses this macro wouldn't compile without that in most use cases (and it's not valid C). See also:Rationale behind the container_of macro in linux/list.h And:container_ofby Greg Kroah-Hartman....
I just ran into this piece of code that does this : ``` delete a, a = 0; ``` It compiles and runs just fine. But isn't this supposed to be : ``` delete a; a = 0; ``` Why is separating statements using , allowed in this case ? Thanks :)
In C and C++, most "statements" are actually expressions. The semicolon added to an expression makes it into a statement. Alternatively, it is allowed (but almost always bad style) to separate side-effectful expressions with the comma operator: the left-hand-side expression is evaluated for its side-effects (and its...
Look at this code ``` h = (c >> 4) & 0xf; l = c & 0xf; printf(h + 'x'); ``` How do I convert this code to C#?
That printf is completely wrong, you are attempting to make a pointer from an integer without a cast and surely you don't want to cast the number to a const char*. Assuming it is meant to print the assumed unsigned integer. The equivalent is: ``` System.Console.WriteLine(120 + (c / 16)); ``` or to be pedantic: ``` ...
I'm importing a C project to Eclipse CDT which has a preinclude header file. I want to know if there's an option to preinclude the file in the projects settings, The projects doesn't compile because of unresolved defines, that needs to be defined in the start. does anyone encountered this before ?
Yes, I've seen such problems several times. If your project doesn't compile, you'll have to change the compiler options, since the compiler needs to know about the file. It depends on your compiler, though, since this is not a C feature.
I wanted to read input from user (multiple lines) and write it into a file using fputs(). Here is my code ``` #include<stdio.h> #include<stdlib.h> int main() { FILE *fp; char s[25]; fp=fopen("myname","w"); if(fp==NULL) { perror("Error opening file\n"); exit(1); } while(fgets(s,25,stdin)!=NULL) fputs(s,...
SinceC-Clikely kills the process, because of buffering, the lines won't get to the file (unless there's a lot of them and they fill the buffer). You should end the output withC-D(Unix) orC-Z(Dos), notC-C. As a side note:fgetsdoesn't strip the newline andfputsadds its own. But I guess you were going to notice that :-...
I am using Visual studio in windows for developing C library. Can someone please provide me simple example of creating thread in windows console application and starting it. Thanks
C++ and C doesn't have support for Threads. You have to use Win32 APIs for threading support for which you can google,BING.
I have a program which does concatenation. its like char *testConc(int a,..) Where a indicates number of arguments are being passed for concatenation. As legth keeps on changing is there is anything like constructor overloading in C or any simple syntax which implements the functionality
Yes, there arevaradic functions ``` #include <stdio.h> #include <stdarg.h> /* print all non-negative args one at a time; all args are assumed to be of int type */ void printargs(int arg1, ...) { va_list ap; int i; va_start(ap, arg1); for (i = arg1; i >= 0; i = va_arg(ap, int)) printf("%d ", i); va...
How can I format string to ensure that it is shown as: ``` ID:12 SIZE:235235235235 ID:1455 SIZE:335235 ``` Instead of: ``` ID:12 SIZE:235235235235 ID:1455 SIZE:335235 ``` Tabs do NOT work in all cases, they only help with this if the length variance is +/- 4-5 characters. Is th...
When you print something withprintf, you can specify a field width; the value is justified in the field. For example: ``` printf("ID: %5d SIZE: %10d", id, size); ``` will right-justify the id in a 5-character field, and the size in a 10-character field.
So this is pretty basic, but I don't really know C. I want to find the number of milliseconds something takes to run, not clock (CPU) cycles. I tried using ``` struct timeval start,end; double dif; gettimeofday(&start, 0); //do stuff gettimeofday(&end, 0); dif = (end - start) / 1000.0; printf("The time taken was %...
Change ``` dif = (end - start) * 1000; ``` to ``` dif = (end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000; ``` In pseudocode: ``` Get the seconds part of the time delta Multiply by 1000 to get milliseconds Get the microseconds part of the time delta Divide that part by 1000 Add that part ...
The MPI spec dictates to callMPI_Finalizein each thread before exiting. How does that work with runtime errors like assertions? If Iassert(cond)andcondevaluates to false, I have no chance to callMPI_Finalizebecause the normal program flow is changed. Am I supposed to catchSIGABRT,SIGSEGVand god-knows-what-else myself...
Write your own version of assert that calls MPI_Finalize after asserting. ``` #define MY_ASSERT(cond) do { \ if (!cond) { \ printf ("Assert (%s) failed at %s:%d\n", #cond, __FILE__, __LINE__); \ MPI_finalize (); \ } \ } while (0); ``` Note that in any case the other MPI processes in your job ...
Can someone explain to me the difference between: int *arr[5]vs.int (*arr)[5]vs.int *(*arr)[5] I'm trying to wrap my mind around how pointers/arrays are actually represented in C...
I would suggest usinghttp://cdecl.org. int *arr[5]"declare arr as array 5 of pointer to int"int (*arr)[5]"declare arr as pointer to array 5 of int"int *(*arr)[5]"declare arr as pointer to array 5 of pointer to int" plus a visit to this page from MSDN:Interpreting more complex declarators.
``` system(do_this); // which executes an external program to output a phrase on the screen printf("=My taxes"); ``` Output: 500$=My taxes Expected output: 500$=My taxes I don't have control over the code executing indo_thiswhich automatically outputs the'\n'.
This should work: ``` system("program | tr -d '\012\015'"); printf("=My taxes\n"); ``` whereprogramis the program you want to run. Thetrcommand removes all CR and LF characters (codes 015 and 012 octal) fromprogram's output. The solution assumesprogramonly outputs one line (your tax) and it works on systems with lin...
I know I can run "ulimit -c unlimited" In the shell to turn on core dumps for the current user. What I am wondering is how can I do this programmatically from C? I see there is a ulimit call, but it's been deprecated in favour of get/setrlimit. What I want to know is what is the equivalent call to setrlimit that wo...
I found a working solution. The core files are now being created. ``` struct rlimit core_limit; core_limit.rlim_cur = RLIM_INFINITY; core_limit.rlim_max = RLIM_INFINITY; if (setrlimit(RLIMIT_CORE, &core_limit) < 0) fprintf(stderr, "setrlimit: %s\nWarning: core dumps may be truncated or non-existant\n", strerror...
I need help with a simplecstructure and can't find it why it's not compiling usinggcc(opensuse 11.4) I have this code: ``` struct Image { int w; int h; // other code }; ``` in the same file I have another struct array like this: ``` struct ShapeImage { Image image[10]; // other code }; ``` when I compile I...
It should be: ``` struct Image image[10] ; ``` Or use typedef while defining the struct: ``` typedef struct { int w; int h; // other code } Image; ``` And use the code otherwise same as in your question.
GCC has a statment expression feature that allows macro to be defined as: ``` #define maxint(a,b) \ ({int _a = (a), _b = (b); _a > _b ? _a : _b; }) ``` This is illegal in Visual Studio. Is there an equivalent feature in microsoft visual studio? (I know, I would better use GCC. But I am just curious). Or, do we ...
There is no equivalent in the MS compiler to this non-standard GCC language extension.
My code snippet looks like this: I want to delay the text in the below inbuilt OpenCV function "cvPutText" so that it appears in the succesive 5or 6 frames. cvPutText (frame_OPENCV,"STRING",cvPoint(60,40),&font,cvScalar(0,0,255,0)); How to display the STRING in 5 successive frames?
You can use the QT backend: the function displayOverlay() allows you to display some text over the image for a given time interval, without modifying the source image displayOverlay()
How to set (in most elegant way) exactlynleast significant bits ofuint32_t? That is to write a functionvoid setbits(uint32_t *x, int n);. Function should handle eachnfrom0to32. Especially valuen==32should be handled.
Here's a method that doesn't require any arithmetic: ``` ~(~0u << n) ```
I have afloatfrom0 to 100and I want to translate that into a number from-20 to 20an example: floatis100then translated it would be-20 floatis50then translated it would be0 floatis0then translated it would be20 What is the best method of doing this?
[I'm going to give you the approach to figuring this out, rather than just the answer, because it'll be more useful in the long-run.] You need a linear transform, of the formy = mx + c, wherexis your input number,yis your output number, andmandcare constants that you need to determine ahead of time. To do so, you ne...
Since Windows Media Player 6.1, Windows has its' own mp3 decoder. Can I use that decoder to get access to the decoded audio (raw) data? I assume it would have to be done with DirectShow. Related but not the same question.
You can add asample grabberinto the graph after the mp3 decoder. The sample grabber allows you to configure a callback that gets called as each sample passes through the media pipeline. Your graph would look something like ``` mp3 file -> mp3 decoder -> sample grabber -> renderer ```
``` #include<stdio.h> int x=13; // forcing space allocation int x; int main(){ printf("%d\n",x); } ``` The code above compiles but the one below does not. why ? ``` #include<stdio.h> int main(){ int x=13; // forcing space allocation int x; printf("%d\n",x); } ``` i was told that int x ; can be interpr...
Quoting: You can't have two global variables with the same name in C program. C might allow multiple definitions in the same file scope through thetentative definition rule, but in any case all definitions will refer to the same variable.
I'm trying to make a simple progress bar like FreeBSD does in its booting screen , displaying / , | , \ , - recursively , but the following code got now output at all ``` #include <stdio.h> #include <unistd.h> int main ( int argc , char **argv ) { char arrows[4] = { '/' , '|' , '\\' , '-' }; int i = 0; ...
You do not flush the output, so it will only be buffered and not flushed to the terminal until the buffer is full. Add the following line after the firstprintf: ``` fflush(stdout); ```
I'm using an API for games. It creates the window for me but there are a few messages I'd like to do something with. For example, when the screen is resizing I want to display a black screen. Essentially, I have the HWND of my main window and would like to listen to the messages and have them go through my custom WndP...
If you are in the same process with the window that you want to intercept WM_SIZE, you can simply replace WndProc bySetWindowLongPtrwithGWLP_WNDPROC. Note that you must pass the other messages to the original WndProc. However, if you are in the different process, then you need to find a way using hooks such asSetWind...
I am looking at the assembly code generated by gcc by using the -s flag. Some statements look like the following. ``` movl is_leader(%rip), destination ``` Here,is_leaderis a globally defined variable of typeintin the C code. What I don't understand is the termis_leader(%rip)here. Isn'tripthe instruction pointer?...
It asks the assembler to generate code that adds or subtracts the difference between the address of the current instruction and the address of the object to the instruction pointer. This gives the address of the object without generating an absolute address (and generally, the offset fits into 16 or 32 bits, so the r...
I have a program which generates its own Wireshark pcap-file (sort of a network log if you havnt used it before). My app uses ANSI-C code to do this. In Android and Windows I simply use 'fopen' and 'fwrite' etc to write file to disc. How does this work on iOS? What is the filepath I will supply to fopen? For example...
You can totally usefopen(I use it in cross-platform code). You do however want to use[documentPath fileSystemRepresentation].
This question already has answers here:Closed11 years ago. Possible Duplicate:How to use dylib in Mac OS X (C++) I have the following files: lost.hlost.dylib I am struggling with the concept of how my C program knows where my lost.dylib file lives? At the top of my file I do an include#include "lost.h"but how does...
At link time it uses a combination of standard directories and user specified directories Linker optionshas more information. Basically using-Loption you can specify more directories to search fordylibthat you are interested in. If you are using Xcode,this link has more details As far as runtime finding of the dyna...
Why won't the following code create a file with permissions read and write for user, group, and other? ``` char data[10] = "123456789"; int fh = open("test.txt", O_RDWR|O_CREAT, 0666); write(fh, data, 10); printf(strerror(errno)); close(fh); ``` Produces this file: ``` -rw-r--r-- 1 pc users 9 Nov ...
Reset youruser maskusing theumask()system call before callingopen().
I have problem with pointers. This is working fine - ``` int main(void){ char *w; w = calloc(20, sizeof(char)); w = "ab"; printf("%c",*w); w = w + sizeof(char); printf("%c",*w); return 0; } ``` but if i use function like: ``` void por(char *t){ t = t + sizeof(char); } ``` and ```...
In your por function, t will not be changed. You need change it ``` void por(char **t){ *t = *t + sizeof(char); } ``` and call it with por(&w)
What does this statement mean? ``` //allocated memory for Device info (*PppsCoreStructure)->psDeviceDetails=(sDeviceDetails **)calloc(CORE_DEVICEINFO_SIZE, sizeof(sDeviceDetails*)); ``` I know that '(*PppsCoreStructure)->psDeviceDetails' is a pointer to pointer. But I am not being able to imagine how calloc can ret...
This call tocallocallocates sufficient space forCORE_DEVICEINFO_SIZEpointers tosDeviceDetailsobjects.callocreturns a simple memory buffer that can be used to store anything; in this case, pointers. (Note that relying oncallocto return buffers filled with null pointers is not portable: it returns zero-filled buffers, ...
I'm writing a macro for slick-edit (with the C similar language slick-C)As far as I found there are no time functions to help me convert epoch time (1321357827) to a human readable date and time (if any of you knows how to do it in slick-C it's great, those of you who doesn't know it - assume C without time.h or any ...
In SE16 you'll find a whole class for date/time manipulation in se/datetime/DateTime.e. In addition, the built-in function_timehas an option to return the epoch time. You should find enough example code there. And for the basic algorithm I found another SO question answered on this:Includes a link to gmtime source. F...
This question already has answers here:Closed11 years ago. Possible Duplicate:What does dot (.) mean in a struct initializer? I have the following structure in which the variables are prefixed with ".". Please kindly help me understand the significance of "." ``` static struct usb_driver skel_driver = { .name =...
Seedesignated initializersin GCC parlance.
Is this understanding correct: any integer that is notsigned char, short, int, long, long longis an extended signed integer type under section 6.2.5/4?
No, not necessarily.int32_tand Co are usually justtypedefs to standard integer types. I don't know of any platform that implements extended integer types in the sense of the standard. On 64 bit platforms gcc e.g has__int128_t(or so), but it doesn't fulfill the requirements of an extended integer type as required by t...
There have been other question/answers on negative array in C in the forum, but i would request the answer to these for a 32-bit compiler : If we have an array definedint test_array[5] = {1,2,3,4,5}; then what should following statements returntest_array[20],test_array[-2],test_array[-32764],test_array[4294967700](va...
It is indefined behaviour as you write it since you are accessing the array out-of-bounds. However, negative indices do not necessarily mean undefined behaviour. The following code is well defined: ``` int test_array[5] = {1,2,3,4,5}; int *p = test_array + 1; int i = p[-1];//i now has the value 1 ``` This is equiva...
I downloaded the source code and wanted to compile the file of scanner. It produces this error: ``` [meepo@localhost cs143-pp1]$ gcc -o lex.yy.o lex.yy.c -ll In file included from scanner.l:15:0: scanner.h:59:5: error: unknown type name ‘bool’ In file included from scanner.l:16:0: utility.h:64:38: error: unknown typ...
C90 does not support the boolean data type. C99 does include it with this include: ``` #include <stdbool.h> ```
I was trying to inject code into the Finder process using mach_inject . I am currently using given the source givenhere The code seems to get the PID of the finder process correctly. There is a bundlemach_inject_bundlewhich is to be injected. The following error comes every time I run the injector. ``` mach_inject...
In the Architectures setting for the project just setx86_64.
I wrote a very simple test code of printf uint64_t: ``` #include <inttypes.h> #include <stdio.h> int main() { uint64_t ui64 = 90; printf("test uint64_t : %" PRIu64 "\n", ui64); return 0; } ``` I use ubuntu 11.10 (64 bit) and gcc version 4.6.1 to compile it, but failed: ``` main.cpp: In function ‘int main()’:...
The ISO C99 standard specifies that these macros must only be defined if explicitly requested. ``` #define __STDC_FORMAT_MACROS #include <inttypes.h> ... now PRIu64 will work ```
My code snippet looks like this: I want to delay the text in the below inbuilt OpenCV function "cvPutText" so that it appears in the succesive 5or 6 frames. cvPutText (frame_OPENCV,"STRING",cvPoint(60,40),&font,cvScalar(0,0,255,0)); How to display the STRING in 5 successive frames?
You can use the QT backend: the function displayOverlay() allows you to display some text over the image for a given time interval, without modifying the source image displayOverlay()
How to set (in most elegant way) exactlynleast significant bits ofuint32_t? That is to write a functionvoid setbits(uint32_t *x, int n);. Function should handle eachnfrom0to32. Especially valuen==32should be handled.
Here's a method that doesn't require any arithmetic: ``` ~(~0u << n) ```
I have afloatfrom0 to 100and I want to translate that into a number from-20 to 20an example: floatis100then translated it would be-20 floatis50then translated it would be0 floatis0then translated it would be20 What is the best method of doing this?
[I'm going to give you the approach to figuring this out, rather than just the answer, because it'll be more useful in the long-run.] You need a linear transform, of the formy = mx + c, wherexis your input number,yis your output number, andmandcare constants that you need to determine ahead of time. To do so, you ne...
Since Windows Media Player 6.1, Windows has its' own mp3 decoder. Can I use that decoder to get access to the decoded audio (raw) data? I assume it would have to be done with DirectShow. Related but not the same question.
You can add asample grabberinto the graph after the mp3 decoder. The sample grabber allows you to configure a callback that gets called as each sample passes through the media pipeline. Your graph would look something like ``` mp3 file -> mp3 decoder -> sample grabber -> renderer ```
``` #include<stdio.h> int x=13; // forcing space allocation int x; int main(){ printf("%d\n",x); } ``` The code above compiles but the one below does not. why ? ``` #include<stdio.h> int main(){ int x=13; // forcing space allocation int x; printf("%d\n",x); } ``` i was told that int x ; can be interpr...
Quoting: You can't have two global variables with the same name in C program. C might allow multiple definitions in the same file scope through thetentative definition rule, but in any case all definitions will refer to the same variable.
I'm trying to make a simple progress bar like FreeBSD does in its booting screen , displaying / , | , \ , - recursively , but the following code got now output at all ``` #include <stdio.h> #include <unistd.h> int main ( int argc , char **argv ) { char arrows[4] = { '/' , '|' , '\\' , '-' }; int i = 0; ...
You do not flush the output, so it will only be buffered and not flushed to the terminal until the buffer is full. Add the following line after the firstprintf: ``` fflush(stdout); ```
I'm using an API for games. It creates the window for me but there are a few messages I'd like to do something with. For example, when the screen is resizing I want to display a black screen. Essentially, I have the HWND of my main window and would like to listen to the messages and have them go through my custom WndP...
If you are in the same process with the window that you want to intercept WM_SIZE, you can simply replace WndProc bySetWindowLongPtrwithGWLP_WNDPROC. Note that you must pass the other messages to the original WndProc. However, if you are in the different process, then you need to find a way using hooks such asSetWind...
I am looking at the assembly code generated by gcc by using the -s flag. Some statements look like the following. ``` movl is_leader(%rip), destination ``` Here,is_leaderis a globally defined variable of typeintin the C code. What I don't understand is the termis_leader(%rip)here. Isn'tripthe instruction pointer?...
It asks the assembler to generate code that adds or subtracts the difference between the address of the current instruction and the address of the object to the instruction pointer. This gives the address of the object without generating an absolute address (and generally, the offset fits into 16 or 32 bits, so the r...
Java code: ``` public class ParentClass { class ChildClass { public String strUrl; /** * Standard Constructor. */ public ChildClass( ) { strUrl = ""; { } // Some code goes here .... } ``` How you can see I haveParentClas...
In oracle java the syntax will be ``` env->FindClass("ParentClass$ChildClass"); ``` This may works also for android. Plus constructor of inner class have additional parameter, reference to outer class.
I'm learning C and now I'm having confusion in pointers. My question is, why doesn't printf("%d", *(i)); return the element instead of address while using multidimensional array?? ``` #include <stdio.h> int main() { int i[2][2] = {{1,8},{2,9},{3, 4}}; //int i[2] = {1,2,3}; printf("%d", *(i)); printf(...
Well, it's an array of arrays, so indexing/dereferencing it once gives you an array, which decays to a pointer...
This question already has answers here:Closed11 years ago. Possible Duplicate:Using C/Pthreads: do shared variables need to be volatile? In Linux/C: Do the global variables shared between threads need to be declared volatile (assume the variable get modified in one of the threads)? What all situations do I need to ...
If you are using pthreads, then no -volatileis neither necessary nor sufficient for correct synchronisation. If your accesses to the global variable are properly protected by a mutex (or another synchronisation primitive), then you can simply declare them as ordinary variables.
I was going through the stdio.h header file that comes with MinGW and noticed that theprintffunction is declared like this: ``` int printf (const char *__format, ...) { //body omitted } ``` I have never seen ellipsis in function parameter list before so I tried it out. It compiles and runs without error. What, t...
That means that the function is a variadic function that takes a variable number of parameters: http://en.wikipedia.org/wiki/Variadic_function printf()itself is probably the best example of a variadic function.
I need to declare an array globally, because I want all methods to be able to access it in the main.c program. However, if I declare it in main.h, I will have to give it a size at declaration time - the problem is, I don't know the size until InitializeMemory(...) method is called, which takes user input to be the siz...
Create it likeint *ptr;globally (let say it's integer); then in your function; ``` ptr = (int *) malloc(100*sizeof(int)); ```
When writing a basic c program. ``` #include <stdio.h> main(){ printf("program"); } ``` Is the definition ofprintfin "stdio.h" or is theprintffunction automatically linked?
Usually, instdio.hthere's only the prototype; the definition should be inside a library that your object module is automatically linked against (the various msvcrt for VC++ on Windows, libcsomething for gcc on Linux). By the way, it's<stdio.h>, not"stdio.h".
What does this do and how? ``` typedef int map_t [1<<MAX]; ``` What does that line do?
AssumingMAXis a constant known at compile-time, then this code: ``` typedef int map_t [1<<MAX]; map_t x; ``` is the same as this code: ``` int x[1 << MAX]; ```
Is it possible to execute a process whose argc = 0? I need to execute a program but it is extremely important for its argc to be equal to 0. Is there a way to do that? I tried to put 2^32 arguments in the command line so that it appears as if argc = 0 but there is a maximum limit to the number of arguments.
You can write a program that callsexecdirectly; that allows you to specify the command-line arguments (including the program name) and lack thereof.
I know open offers these mutually exclusive flags:O_RDONLY,O_WRONLYandO_RDWR. I want to know: Are there any performance issues (even of it's just a fraction of a ms) or different ways of treating the file if the file is opened asO_RDWRand I only write to the file. (Versus opening as O_WRONLY)I only read data from th...
First, you seem to have mistyped (inverted) in the two cases of your description the write/read tags. As to what you ask, the VFS, in its various structures, keeps track of desired access rights by flags. The read/write flag is typically a different bit in the same flag (multi) byte. When a process request access as r...
I have a C linux function which has the following code: ``` void A (char *s1, char *s2) { ... *s2 = NULL; ... } ``` in this function I put values into s2, and at the end put NULL. the code: ``` *s2 = NULL ``` generates the following warning: assignment makes integer from pointer without a cast I want to fix my c...
Your system appears to haveNULLdefined as something like(void *)0. That means your assignment is doing just what the warning says - making an integer from a pointer without a cast. You don't want to putNULLinto acharvariable anyway - you are probably looking for: ``` *s2 = '\0'; ```
I've searched around and haven't found an answer to this. What I would like to know is this: If I declare astatic unsigned char const ARRAY[256] = { [0] = <some_value> };, can I expect the unspecified elements (in this case all but the element at index0) to have a certain value, or will they be random? I need this ...
The rest of the array will be initialized to zero. Also, you may initialize more than one element in the array, for example: ``` char arr[10] = {1, 2, 3}; ``` will create and initialize the array arr to: ``` index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 --------------------------------------------- value | 1 | 2 |...
Why does this loop (to 1 billion) only take a few sounds to execute ... ``` for (i = 0; i < 1000000000; i++) { } ``` ... but this loop (to 10 billion) takes >10 minutes? ``` for (i = 0; i < 10000000000; i++) { } ``` Shouldn't it just take 30 seconds or so (3 seconds x 10)?
I guessiis a 32-bit integer variable and is therefore always smaller than 10 billion (which is more than 2^32), whereas 1 billion still fits into the 32-bit range (which ends at about 2 or 4 billion, depending on signedness). Though I don't know how the compiler promotes this 10 billion constant, but he seems to reali...
I've been working on a project in C that requires me to mess around with strings a lot. Normally, I do program in C++, so this is a bit different than just saying string.empty(). I'm wondering what would be the proper way to empty a string in C. Would this be it? ``` buffer[80] = "Hello World!\n"; // ... strcpy(...
It depends on what you mean by "empty". If you just want a zero-length string, then your example will work. This will also work: ``` buffer[0] = '\0'; ``` If you want to zero the entire contents of the string, you can do it this way: ``` memset(buffer,0,strlen(buffer)); ``` but this will only work for zeroing up ...
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 have a pointer to an wide char array, which I want to free. What is the easiest way to do this?
That depends on how the memory was allocated. Ifmalloc()was used, pass the address of the allocated memory tofree(). If it came from a third-party library, see that library's documentation. If the struct is actually a local or global variable, don't worry about cleaning it up at all.
I have 2 functions inCdoing exactly the same thing, the only difference is the data types passed to each function e.g. one is int the other one char* . Is there a way to combine these functions to one so that when I call this one function I need not worry about the data type. This can be done in C++ using template but...
I know two common ways to deal with such situtation in C.1)Replace int and "char *", with "void *p" and "int size" ``` void f1(int i); void f2(char *str); -> void f(void *p, int s); f(&i, sizeof(i)); f(str, strlen(str);//or may be f(str, sizeof(str[0]); ``` for example seeqsortfrom stdlib 2)Use preprocessor, like ...
This is from Beej's guide to C"The drawback to using calloc() is that it takes time to clear memory, and in most cases, you don't need it clear since you'll just be writing over it anyway. But if you ever find yourself malloc()ing a block and then setting the memory to zero right after, you can use calloc() to do that...
When the function you are passing a buffer to states in its documentation that a buffer must be zero-filled. You may also always zero out the memory for safety; it doesn't actually take that much time unless the buffers are really huge. Memory allocation itself is the potentially expensive part of the operation.
I need some help on creating a function similar to theputenv()function of the C standard library, but instead of: ``` int putenv(char *string); ``` it is prototyped as: ``` void env_add(char varname[], char varvalue[]); ``` wherevarname[]andvarvalue[]are entered by the user and are of type char.
You should measure the length ofvarnameandvarvalue(with e.g.strlen), allocate dynamically a string long enough to hold them, the equal sign and the null terminator, build thevarname=varvaluestring (you can do that with e.g.snprintforstrncat, or with twoforloops if you are the masochist type), pass the new string toput...
A language has not array as a data type but it has stack as a data type and one can declare stack's; andpush,popandisemptyoperations are defined.So how can we implement array using two stacks and above operations?
Horribly inefficient - but: Stack 1 Contains the details Stack 2 is empty. To go through the array, Pop Stack 1 , when you want the next one, push the previous one into stack 2 and pop stack 1 again. Repeat until 'isempty'. If you want the Nth value, pop the not empty stack N times while pushing the unneeded ones i...
When I run this code, it iterates, but then returns "The answer is 0", when it should be "The answer is 10." Why is this? ``` #import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { int i; for (int i = 0; i < 12; i++){ if (i % 3 == 0) { continue; } ...
``` int i; for (int i = 0; i < 12; i++){ ^^^^^ ``` Theiinside the loop is not the same as theioutside the loop. Repace that with: ``` int i; for (i = 0; i < 12; i++){ ```
I have a short question about my code. I've created two situation or examples for testing. example 1: ``` char *arr[1000000]; int i = 0; for (; i < 1000000; i++){ char *c = (char *) calloc(1, sizeof(char) * 10); free(c); } ``` example 2: ``` char *arr[1000000]; int i = 0; for (; i < 1000000; i++){ char...
The result are the same. I'm not sure why you think there are differences.
I'm doing my college's task. I wrote like this ``` int debut[10][100]; char ngroup[10][100]; do { printf("1. Group name [1..25] : "); gets (ngroup[0]); }while (strlen(ngroup[0])< 1 || strlen(ngroup[0])>25); do { printf("2. Year debute [1900-2011] : "); scanf("%d",&debut[0]); } while (debut[0] < 1900 ...
debut[0]is a pointer to array of 100 ints, and you try to compare it with an integer value. You need something like this: ``` int debut[10]; ... scanf("%d",&debut[0]); } while (debut[0] < 1900 || debut[0] > 2011); ```