question
stringlengths
25
894
answer
stringlengths
4
863
How can I convert the char arrayxto an integer89in the code below? Thank you ``` int main(int argc,char *argv[]){ char y[13] = "0123456789012"; char x[3]; int integer_value; x[0] = y[8]; x[1] = y[9]; x[3] = '\0'; integer_value=atoi(x); } ```
You're done;atoi()is one way of doing the conversion from a string to an integer. You could also usestrtol()orsscanf(). UPDATE:Assuming, of course, that you fix the termination, i.e. setx[2] = '\0';rather thanx[3].
By the fact if I includestdlib.hinto each file of my program and I do not get an re-definition error. So, the answer is yes. Right? I'm reading thelibxml2source code, and inHTMLparser.cthere is this part: ``` #include <string.h> #ifdef HAVE_CTYPE_H #include <ctype.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #...
Those aren't include guards. These macros are set if the corresponding headers are present in the system, resp. detected during configuration. If they were included unconditionally and they are not present, the compilation would fail.
This question already has answers here:Closed11 years ago. Possible Duplicate:Why can't variables be declared in a switch statement?How can a variable be used when its definition is bypassed? ``` #include<stdio.h> int main() { int a=1; switch(a) { int b=20; case 1: printf("b is %d\n...
Initialization of variables inside switch statements is bad practice and undefined behavior.
I was trying to test one of the K&R function which uses c-'0'. To understand clearly I wrote a two line code as below. My question is why is it printing "1". And what does the "numeric value" actually mean in this context. Thanks! ``` char c = 'a'; printf("%c",c-'0'); ```
c - '0'only has a definite specific value when c is a digit ('0', '1', ..., or '9'). Whencis'0','0' - '0'is0because they are equal whencis'1','1' - '0'is1because'1'immediately follows'0'in any character set any C implementation choses to use. The same for'2'and the other digits:'9' - '0'has a value of9. And you real...
I was looking at gettingHTML-XML-Utilsworking on my computer and I noticed the .e filetype in the source tree. Running: ``` % file types.e types.e: ASCII c program text ``` reveals some clues about it and its use in C files seems to be that of a header file. Can anyone reveal some more information or history about ...
I never heard of that file type in connection with C before, but after checking the files and the Makefile it seems to be variables and functions that areexported, therefore the.eextension. They seem to be created by a special program (which comes with the package) calledcexportwhose manual page states: cexport - cr...
I'm learning some file functions and hence have a doubt. I'm curious about why it is necessary to callclose()to close a file? If I did not callclose()after reading/writing a file, what things might happen? And if I did callclose(),can I still use the file descriptor?
If the file has any sort of buffering behind it it and you don't call close then you could potentially lose data.If the OS has limited resources (e.g. number of open files) then by not closing files you are wasting system resources.Using a descriptor once the file is closed is pointless at best, massive bug at worst (...
I need to do some registry operations & other system operations for that i need admin permission. currently user have to start my application as "Run as administrator". so How could i launch my application with admin rights?
CreateProcessAsUserorCreateProcessWithLogonWis the main thing you need. ForCreateProcessAsUser, you'll need to use a few other things to make it do its tricks though (e.g.,AdjustTokenPrivilegesto enable the privileges it uses, andLogonUserto get a user's token).
Is there a simple way to get time time of day (17:30, 01:20...etc) that would work on iOS, OSX, Linux and Windows? If not is there a Windows way and a posix way or something? Thanks
You can retrieve the time withtime_t now = time(NULL);ortime(&now); You then usually convert to local time withstruct tm *tm_now = localtime(&now);. Astruct tmcontains fields for the year, month, day, day of week, hour, minute, and second. If you want to produce printable output,strftimesupports that directly. Both ...
I'm doing a project with a lot of calculation and i got an idea is throw pieces of work to GPU, but i wonder whether could we retrieve results from GLSL, if it is posible, how?
GLSL does not provide outputs besides what is placed in the frame buffer. To program a GPU and get results more conveniently, useCUDA(NVidia only) orOpenCL(cross-platform).
I have a string x that I need to convert into a hex format: ``` char x[5]; x[0]='0'; x[1]='1'; x[2]='0'; x[3]='1'; //x contains value of 0xA or decimal 10; x[4]='\0'; ``` Now how can I convert this and store it into an unsigned integer variable so the variable would be of value 0xA; Thanks.
It seems that the number is stored in reversed direction, which is not natural for human to read, but quite a natural way to represent number as the index refers to the power of 2 that should be applied. There is no existing library to do the conversion for you, you need to write code to parse it yourself: ``` int i...
I have a project and two files in the project are named asquery-structures.hquery-structures.c. Contents in thequery-structures.hare ``` #include <stdint.h> typedef struct user_identifier user_identifier; extern user_identifier; ``` and inquery-structures.care ``` #include "query-structures.h" struct user_identifie...
This line is abnormal because you declare a type but no variable name ``` extern user_identifier; ``` For example, with ints, you would write ``` extern int x; ``` not ``` extern int; ```
I run the following command to link the different files in my project. ``` /opt/gcc-4.7-cilkplus/bin/gcc -g -Wall -l /opt/gcc-4.7-cilkplus/lib64/ -o exec main.o \ mysql-client.o databaseConnection-common.o murmurhash3.o bloom-filter.o `mysql_config --cflags --libs\` -lcilkrts ``` Note the option-l /opt/gcc-4...
-l (el) should be followed by a library, not a directory. Perhaps you meant -L or -I (eye)
I typically acquire a character with%c, but I have seen code that used%*c%c. For example: ``` char a; scanf("%*c%c", &a); ``` What is the difference?
In ascanfformat string, after the%, the*character is theassignment-suppressing character. In your example, it eats the first character but does not store it. For example, with: ``` char a; scanf("%c", &a); ``` If you enter:xyz\n, (\nis the new line character) thenxwill be stored in objecta. With: ``` scanf("%*c%...
I'm writing a SQL embedded in C program with tables below: ``` table index:id, xx table a:id, year, yy table b:id, year, zz table c:id, year, vv ``` id in a,b,c belong to id in index Then how to select all the id order by year?
You question is not very clear about what you are after. Superficially, one possible answer might be: ``` SELECT i.id, i.xx, a.year, a.yy FROM index AS i JOIN a ON i.id = a.id UNION SELECT i.id, i.xx, b.year, b.zz FROM index AS i JOIN b ON i.id = b.id UNION SELECT i.id, i.xx, c.year, c.vv FROM index AS i ...
If I create a file in ubuntu like this: "echo "asd" > file.txt" and I do a ls -l file.txt it says that it's size is 4 bytes, but I only wrote 3 (asd). If I do "cat file.txt" it shows the 3 chars that I have added. Why is the file 4 bytes large?
asd+ new line character = 4 bytes ``` $ echo asd | wc -c 4 $ echo -n asd | wc -c 3 $ echo asd | hd 00000000 61 73 64 0a |asd.| 00000004 ``` -n in echo switches newline off hdshows you a hexdump of the stream. You see the0acharacter at the end. That is the fourth character, new...
How can I convert the char arrayxto an integer89in the code below? Thank you ``` int main(int argc,char *argv[]){ char y[13] = "0123456789012"; char x[3]; int integer_value; x[0] = y[8]; x[1] = y[9]; x[3] = '\0'; integer_value=atoi(x); } ```
You're done;atoi()is one way of doing the conversion from a string to an integer. You could also usestrtol()orsscanf(). UPDATE:Assuming, of course, that you fix the termination, i.e. setx[2] = '\0';rather thanx[3].
By the fact if I includestdlib.hinto each file of my program and I do not get an re-definition error. So, the answer is yes. Right? I'm reading thelibxml2source code, and inHTMLparser.cthere is this part: ``` #include <string.h> #ifdef HAVE_CTYPE_H #include <ctype.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #...
Those aren't include guards. These macros are set if the corresponding headers are present in the system, resp. detected during configuration. If they were included unconditionally and they are not present, the compilation would fail.
This question already has answers here:Closed11 years ago. Possible Duplicate:Why can't variables be declared in a switch statement?How can a variable be used when its definition is bypassed? ``` #include<stdio.h> int main() { int a=1; switch(a) { int b=20; case 1: printf("b is %d\n...
Initialization of variables inside switch statements is bad practice and undefined behavior.
I was trying to test one of the K&R function which uses c-'0'. To understand clearly I wrote a two line code as below. My question is why is it printing "1". And what does the "numeric value" actually mean in this context. Thanks! ``` char c = 'a'; printf("%c",c-'0'); ```
c - '0'only has a definite specific value when c is a digit ('0', '1', ..., or '9'). Whencis'0','0' - '0'is0because they are equal whencis'1','1' - '0'is1because'1'immediately follows'0'in any character set any C implementation choses to use. The same for'2'and the other digits:'9' - '0'has a value of9. And you real...
I was looking at gettingHTML-XML-Utilsworking on my computer and I noticed the .e filetype in the source tree. Running: ``` % file types.e types.e: ASCII c program text ``` reveals some clues about it and its use in C files seems to be that of a header file. Can anyone reveal some more information or history about ...
I never heard of that file type in connection with C before, but after checking the files and the Makefile it seems to be variables and functions that areexported, therefore the.eextension. They seem to be created by a special program (which comes with the package) calledcexportwhose manual page states: cexport - cr...
I am confused as to how we are able to return strings from function. ``` char* someFunction() { return "Hello, World" } ``` Shouldn't the above return statement throw "function returns address of local variable" and how is it different from the function: ``` char* newFunction() { char temp[] = "Hello, World"; ...
In the first case, the string lives in constant readonly memory at a fixed address for all time. In the second case, the string is put locally on the stack, and so is temporary.
If I omit the operators from statement, something like this:while(foo)will the compiler turn it inwhile(foo != NULL || *foo != '\0' || foo != 0)orwhile(!foo)or something like this? how to it is really done?
while (condition)just checks forconditionbeing non-zero. Therefore these two are equivalent: ``` while (foo) while (foo != 0) ```
My question has two parts: Is it possible that, if a segfault occurs after allocating memory but before freeing it, this leaks memory (that is, the memory is never freed resulting in a memory leak)?If so, is there any way to ensure allocated memory is cleaned up in the event of a segfault? I've been reading about me...
In the event of a seg fault, the OS is responsible for cleaning up all the resources held by your program. Edit: Modern operating systems will clean up any leaked memory regardless of how your program terminates. The memory is only leaked for the life of your program. Most OS's will also clean up many other types ...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. I program in Java, C and Python. T...
Coercion is another name for animplicittype cast, i.e. one mandated by the language rules, and not explicitly added by the programmer.
I found this line of code in some code I'm analyzing: ``` Mintau = (double*) malloc(FadeAll.num_paths*sizeof(double)); ``` I also found a question on here (that was a duplicate of other questions it appears) that explains different syntax of pointers including: ``` int *ptr; int * ptr; int* ptr; ``` I should e...
There are no difference between this three declarations: ``` int *ptr; int * ptr; int* ptr; ``` (double*)has to be in parenthesis because it is a Cast. Read a little about casting in thislink Hope it helps.
How does this code work toFind the next highest power of 2 for any given number [>1] for 32 bit integer? ``` n--; n = n | n>>1; n = n | n>>2; n = n | n>>4; n = n | n>>8; n = n | n>>16; n++; ```
The sequence of shifts and bitwise-ors guarantees a number that consists of all1s, which is one less than a power-of-2. Adding 1 to it gives a power-of-2. The initial decrement by 1 is to make it work for values ofnthat are already powers-of-2. (Obviously, this code doesn't work ifnis originally0.)
Maybe I'm missing something, but here is a problem: I'm tracing python code by C extensions and my trace function got PyFrameObject* frame. Now I want to process the frame by Python code(embedded or converted to C by Cython) but it deals with PyObject*. How do I convert PyFrameObject* to PyObject*? I don't find appr...
Use a cast: ``` PyObject *myObject = (PyObject *)myFrameObject ``` This is standard for the Python C API; everything that "inherits" fromPyObjecthas aPyObject_VAR_HEADat the top of the object so a pointer to the object is convertible to a pointer toPyObject.
I have an array of structs. Actually, it is a 2d-array but an unusual 2d array. I am allocating memory on stack: ``` #define MAX_VERTICES 5068 struct ARRAY_FIX { int ele[MAX_VERTICES]; int size; int first; }; ARRAY_FIX C[MAX_VERTICES]; int main() { //... } ``` So, I need to replace one row with another...
You can use an array of pointers tostruct ARRAY_FIXand just switch the pointers into the array. I am allocating memory on stack. An object declared at file scope is usually NOT on the stack.
I cannot understand what is the difference between: ``` #define WIDTH 10 ``` and ``` int width = 10; ``` What are the benefits of using the first or the second?
Well, there is a great difference. You can change the value ofwidth, you can take its address, you can ask for its size and so on. WithWIDTH, it will be just replaced with a constant10everywhere, so the expression++WIDTHdoesn't make any sense. Ono the other side, you can declare an array withWIDTHitems, whereas you ca...
I came across the following code : ``` int i; for(; scanf("%s", &i);) printf("hello"); ``` As per my understanding, if we provide integer inputscanfwould be unsuccessful in reading and therefore return 0, thus the loop should not run even once. However, it runs infinitely by accepting all types of inputs as succ...
That is the incorrect format specifier for anint: should be"%d". It is attempting to read a string into anintvariable, probably overwriting memory. As"%s"is specified, all inputs will be read thusscanf()returns a value greater than zero.
I found this line of code in some code I'm analyzing: ``` Mintau = (double*) malloc(FadeAll.num_paths*sizeof(double)); ``` I also found a question on here (that was a duplicate of other questions it appears) that explains different syntax of pointers including: ``` int *ptr; int * ptr; int* ptr; ``` I should e...
There are no difference between this three declarations: ``` int *ptr; int * ptr; int* ptr; ``` (double*)has to be in parenthesis because it is a Cast. Read a little about casting in thislink Hope it helps.
How does this code work toFind the next highest power of 2 for any given number [>1] for 32 bit integer? ``` n--; n = n | n>>1; n = n | n>>2; n = n | n>>4; n = n | n>>8; n = n | n>>16; n++; ```
The sequence of shifts and bitwise-ors guarantees a number that consists of all1s, which is one less than a power-of-2. Adding 1 to it gives a power-of-2. The initial decrement by 1 is to make it work for values ofnthat are already powers-of-2. (Obviously, this code doesn't work ifnis originally0.)
Maybe I'm missing something, but here is a problem: I'm tracing python code by C extensions and my trace function got PyFrameObject* frame. Now I want to process the frame by Python code(embedded or converted to C by Cython) but it deals with PyObject*. How do I convert PyFrameObject* to PyObject*? I don't find appr...
Use a cast: ``` PyObject *myObject = (PyObject *)myFrameObject ``` This is standard for the Python C API; everything that "inherits" fromPyObjecthas aPyObject_VAR_HEADat the top of the object so a pointer to the object is convertible to a pointer toPyObject.
I have an array of structs. Actually, it is a 2d-array but an unusual 2d array. I am allocating memory on stack: ``` #define MAX_VERTICES 5068 struct ARRAY_FIX { int ele[MAX_VERTICES]; int size; int first; }; ARRAY_FIX C[MAX_VERTICES]; int main() { //... } ``` So, I need to replace one row with another...
You can use an array of pointers tostruct ARRAY_FIXand just switch the pointers into the array. I am allocating memory on stack. An object declared at file scope is usually NOT on the stack.
I cannot understand what is the difference between: ``` #define WIDTH 10 ``` and ``` int width = 10; ``` What are the benefits of using the first or the second?
Well, there is a great difference. You can change the value ofwidth, you can take its address, you can ask for its size and so on. WithWIDTH, it will be just replaced with a constant10everywhere, so the expression++WIDTHdoesn't make any sense. Ono the other side, you can declare an array withWIDTHitems, whereas you ca...
I came across the following code : ``` int i; for(; scanf("%s", &i);) printf("hello"); ``` As per my understanding, if we provide integer inputscanfwould be unsuccessful in reading and therefore return 0, thus the loop should not run even once. However, it runs infinitely by accepting all types of inputs as succ...
That is the incorrect format specifier for anint: should be"%d". It is attempting to read a string into anintvariable, probably overwriting memory. As"%s"is specified, all inputs will be read thusscanf()returns a value greater than zero.
I have an array with a size that I dont know(mostly a size of a 10), that most of it has 1's and 2's, but sometimes 3's and 4's... I cant buble sort, because the order is importhan, but other then that, I can do everything Thanks :)
Iterate over the array until you hit your break condition. While iterating (use thefororwhileloop), remember the highest value so far and compare against current.
There is a file of 1 GB contains a single string of characters. As the string is very large it can't be loaded completely to memory. What is the best way to reverse this string?
load blocks into memory, iterate through them in reverse while writing them out in order. pseudocode: ``` load_block(buffer, 4mb, end of file); // Load a 4mb block from the end for (i = 4mb; i>=0; i--) { write(buffer[i],1); // Write it out in reverse } ```
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
You could use libxml2. Despite its name it includes a HTML parserHTML Parser module - libxml2.I have used the python binding, it's fast and supports XPath.
i'm writing an app that needs a calculation support (Fun project). However, is there a way to enter input data to the interactive console in BC from C#, and then read the data from the console with C#? I have tried to use dllexport in the c source, but the code is confusing me.
The usual way to interact with prewritten console applications in c# is to useProcess.Startand then redirectStandardInputandStandardOutput.
I've done some research, but I didn't find an answer to my question. I would like to know how to determine if the used charset in a C program is ASCII. Are there any preprocessor constants ? Many thanks.
C says: (C99, 5.2.1p1) "The values of the members of the execution character set are implementation-defined." For examplegccsays: The values of the members of the execution character set (C90 and C99 5.2.1).Determined by ABI http://gcc.gnu.org/onlinedocs/gcc/Characters-implementation.html Sogccpoints to the...
Is there any control that can be used for drawing a diagram like this in winapi32 controles? in not do you have any idea how can I draw one? (something like this!)
You will find third party chart control for the Windows APIs -http://www.gigasoft.com/graphinglibrary.htmlhttp://www.codeproject.com/Articles/14330/Custom-Control-Graph-and-Process-Bar Or you can draw the line graph yourself using the GDI functionsLineToandMoveTo.
I'm building a c/c++ program and I'm using MS Excel for results representation. The problem is that i have to import 2 files: ``` #import "C:\Program Files (x86)\Common Files\microsoft shared\OFFICE14\MSO.DLL" #import "C:\Program Files (x86)\Microsoft Office\Office14\EXCEL.EXE" ``` It works perfectly on my compu...
Import is performed by preprocessor, so you can't do it in runtime, i.e. you have to know all paths before compilation is started
``` #include <stdio.h> #define next(x) x + 1 #define prev(x) x - 1 #define mult(x,y) x * y int main(void) { int a = 3, b = 4; printf("%d\n", mult(next(a), prev(b))); return 0; } ``` mult(next(3),prev(4))expands tomult(3+1, 4-1)which is 12. But the answer is 6. Why is that?
... andmult(3+1, 4-1)expands to ``` 3+1 * 4-1 ``` which results in 3 + 4 - 1 or 6. In a function like macro definition put parenthesis around each and every parameter and around the whole definition ``` #define next(x) ((x) + 1) #define prev(x) ((x) - 1) #define mult(x, y) ((x) * (y)) ```
I am looking for a possibility within C/C++ to print a float (or double) f, sayf = 1.234e-15, such that it is printed as f = 1.234*10^-15, or, even better, asf = 1.234*10^{-15} Can anyone help me? Maybe there is a way to get the exponent "-15" and mantissa "1.234" in base 10. I found the questionhow can I extract th...
You can print to astringusing the output string stream, and then replace"e"with"*10^". ``` ostringstream ss; ss << scientific << 123456789.87654321; string s = ss.str(); s.replace(s.find("e"), 1, "*10^"); cout << s << endl; ``` This snippetproduces ``` 1.234568*10^+08 ```
Where areSTRINGandWM_NAMEdefined? Myxcb_atom.hfile only contains 3 function declarations, when I was expecting it to look like this:http://www.opensource.apple.com/source/X11libs/X11libs-40/xcb-util/xcb-util-0.3.3/atom/xcb_atom.h I also have axcb_ewmh.hfile that contains similar atoms but I cannot find any documenta...
As noted in the other answer, the symbols are inxproto.hwhich is dragged in byxcb.h, but are not named as in the XCB tutorial. You need to useXCB_ATOM_WM_NAMEandXCB_ATOM_WM_STRING.
What is default calling convention for a static function say: ``` static void PrintHelloWorld(char* s) { } ``` under Linux: ``` #36-Ubuntu SMP Tue Apr 10 20:39:51 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux ``` and with ``` gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 Linux ubuntu 3.2.0-23-generic ```
Under the architecture and compiler you have listed (Linux x86_64), the calling convention described in theSystem V AMD64 ABIis used. Under Linux i386, the calling convention described in theSystem V i386 ABIis used.
I was wondering if I could make a large number of system calls at the same time, with only one switch overhead. I need this because I have a need to make many (128) system calls at the same time. If I could do this without switching between kernel and userland 256+ times I think it could make my (speed sensitive) libr...
You really can't do that from an application program. What youcoulddo is build a loadable kernel module that implements those operations and presents a simple API -- then you can change context once, do all the work, and return. However, as with most of these sorts of optimization questions, the first thing to ask i...
I am new to C and writing a simple program to display the byte representation of data. When I compile, the Command Prompt screen flashes for 1/2 a second and disappears. In simpler words, the output doesn't show up. Following is my code: ``` #include <stdio.h> typdef unsigned char* pointer; void show_int(int); void ...
The program likely is displaying your output, then quickly exiting. You'll want to delay before exiting. If you're on Windows, use Sleep(milliseconds); if you're on Unix, use sleep(seconds). Note not only the different units, but the different capitalization.
Here's an example I saw for some GLX code: ``` display = XOpenDisplay(0); // ... xcb_connection_t *connection = XGetXCBConnection(display); // ... XCloseDisplay(display); ``` I noticed that there was noxcb_disconnectin there. Is this correct? Also, isconnectionstill valid after the display is closed?
XCloseDisplayseems to undo the creation of the display (hence destroying it), and since the XCB connection object is derived from the display, it would seem reasonable that the connection becomes invalidated once the display is closed.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. I am very new to the Xcode environm...
You should create aCommand Line Toolproject, not Generic C++ Plugin. Once you do that, your output will show up in the console window in xcode.
I have an array ofchar *like this: ``` char * gradient_xpm[] = {"abc", "def", "ghi"}; ``` I need to change the value of those strings. I've triedstrcpyand the=operator, but it gives me a Segmentation Fault. e.g: ``` strcpy(gradient_xpm[1],"jkl"); gradient_xpm[1][2] = 'x'; ``` I wasn't able to edit even a single ...
You have string constants in your array, and those can't be changed. This is the cause of your segfaults. You'll need to setup your array without using string constants, then copy the string constants into your array. Something like: ``` char *gradient_xpm[3]; gradient_xpm[1] = (char *) malloc(sizeof(char) * (MAX_...
Was reading through some text and playing around with attempting to write past the size of an array in C i.e buffer overflow. The text indicates that whenever you attempt to write to sayarray[5]when the length of the array is 5 then you get a segmentation fault but I dont seem to be getting that When using the code be...
Writing past the end is Undefined Behaviour- anything may happen.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
You could use libxml2. Despite its name it includes a HTML parserHTML Parser module - libxml2.I have used the python binding, it's fast and supports XPath.
i'm writing an app that needs a calculation support (Fun project). However, is there a way to enter input data to the interactive console in BC from C#, and then read the data from the console with C#? I have tried to use dllexport in the c source, but the code is confusing me.
The usual way to interact with prewritten console applications in c# is to useProcess.Startand then redirectStandardInputandStandardOutput.
I've done some research, but I didn't find an answer to my question. I would like to know how to determine if the used charset in a C program is ASCII. Are there any preprocessor constants ? Many thanks.
C says: (C99, 5.2.1p1) "The values of the members of the execution character set are implementation-defined." For examplegccsays: The values of the members of the execution character set (C90 and C99 5.2.1).Determined by ABI http://gcc.gnu.org/onlinedocs/gcc/Characters-implementation.html Sogccpoints to the...
Is there any control that can be used for drawing a diagram like this in winapi32 controles? in not do you have any idea how can I draw one? (something like this!)
You will find third party chart control for the Windows APIs -http://www.gigasoft.com/graphinglibrary.htmlhttp://www.codeproject.com/Articles/14330/Custom-Control-Graph-and-Process-Bar Or you can draw the line graph yourself using the GDI functionsLineToandMoveTo.
I'm building a c/c++ program and I'm using MS Excel for results representation. The problem is that i have to import 2 files: ``` #import "C:\Program Files (x86)\Common Files\microsoft shared\OFFICE14\MSO.DLL" #import "C:\Program Files (x86)\Microsoft Office\Office14\EXCEL.EXE" ``` It works perfectly on my compu...
Import is performed by preprocessor, so you can't do it in runtime, i.e. you have to know all paths before compilation is started
``` #include <stdio.h> #define next(x) x + 1 #define prev(x) x - 1 #define mult(x,y) x * y int main(void) { int a = 3, b = 4; printf("%d\n", mult(next(a), prev(b))); return 0; } ``` mult(next(3),prev(4))expands tomult(3+1, 4-1)which is 12. But the answer is 6. Why is that?
... andmult(3+1, 4-1)expands to ``` 3+1 * 4-1 ``` which results in 3 + 4 - 1 or 6. In a function like macro definition put parenthesis around each and every parameter and around the whole definition ``` #define next(x) ((x) + 1) #define prev(x) ((x) - 1) #define mult(x, y) ((x) * (y)) ```
I am looking for a possibility within C/C++ to print a float (or double) f, sayf = 1.234e-15, such that it is printed as f = 1.234*10^-15, or, even better, asf = 1.234*10^{-15} Can anyone help me? Maybe there is a way to get the exponent "-15" and mantissa "1.234" in base 10. I found the questionhow can I extract th...
You can print to astringusing the output string stream, and then replace"e"with"*10^". ``` ostringstream ss; ss << scientific << 123456789.87654321; string s = ss.str(); s.replace(s.find("e"), 1, "*10^"); cout << s << endl; ``` This snippetproduces ``` 1.234568*10^+08 ```
Where areSTRINGandWM_NAMEdefined? Myxcb_atom.hfile only contains 3 function declarations, when I was expecting it to look like this:http://www.opensource.apple.com/source/X11libs/X11libs-40/xcb-util/xcb-util-0.3.3/atom/xcb_atom.h I also have axcb_ewmh.hfile that contains similar atoms but I cannot find any documenta...
As noted in the other answer, the symbols are inxproto.hwhich is dragged in byxcb.h, but are not named as in the XCB tutorial. You need to useXCB_ATOM_WM_NAMEandXCB_ATOM_WM_STRING.
What is default calling convention for a static function say: ``` static void PrintHelloWorld(char* s) { } ``` under Linux: ``` #36-Ubuntu SMP Tue Apr 10 20:39:51 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux ``` and with ``` gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 Linux ubuntu 3.2.0-23-generic ```
Under the architecture and compiler you have listed (Linux x86_64), the calling convention described in theSystem V AMD64 ABIis used. Under Linux i386, the calling convention described in theSystem V i386 ABIis used.
I was wondering if I could make a large number of system calls at the same time, with only one switch overhead. I need this because I have a need to make many (128) system calls at the same time. If I could do this without switching between kernel and userland 256+ times I think it could make my (speed sensitive) libr...
You really can't do that from an application program. What youcoulddo is build a loadable kernel module that implements those operations and presents a simple API -- then you can change context once, do all the work, and return. However, as with most of these sorts of optimization questions, the first thing to ask i...
I am new to C and writing a simple program to display the byte representation of data. When I compile, the Command Prompt screen flashes for 1/2 a second and disappears. In simpler words, the output doesn't show up. Following is my code: ``` #include <stdio.h> typdef unsigned char* pointer; void show_int(int); void ...
The program likely is displaying your output, then quickly exiting. You'll want to delay before exiting. If you're on Windows, use Sleep(milliseconds); if you're on Unix, use sleep(seconds). Note not only the different units, but the different capitalization.
Here's an example I saw for some GLX code: ``` display = XOpenDisplay(0); // ... xcb_connection_t *connection = XGetXCBConnection(display); // ... XCloseDisplay(display); ``` I noticed that there was noxcb_disconnectin there. Is this correct? Also, isconnectionstill valid after the display is closed?
XCloseDisplayseems to undo the creation of the display (hence destroying it), and since the XCB connection object is derived from the display, it would seem reasonable that the connection becomes invalidated once the display is closed.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. I am very new to the Xcode environm...
You should create aCommand Line Toolproject, not Generic C++ Plugin. Once you do that, your output will show up in the console window in xcode.
I have an array ofchar *like this: ``` char * gradient_xpm[] = {"abc", "def", "ghi"}; ``` I need to change the value of those strings. I've triedstrcpyand the=operator, but it gives me a Segmentation Fault. e.g: ``` strcpy(gradient_xpm[1],"jkl"); gradient_xpm[1][2] = 'x'; ``` I wasn't able to edit even a single ...
You have string constants in your array, and those can't be changed. This is the cause of your segfaults. You'll need to setup your array without using string constants, then copy the string constants into your array. Something like: ``` char *gradient_xpm[3]; gradient_xpm[1] = (char *) malloc(sizeof(char) * (MAX_...
Was reading through some text and playing around with attempting to write past the size of an array in C i.e buffer overflow. The text indicates that whenever you attempt to write to sayarray[5]when the length of the array is 5 then you get a segmentation fault but I dont seem to be getting that When using the code be...
Writing past the end is Undefined Behaviour- anything may happen.
In some Bison code, what does the following line mean? ``` #define YY_DECL extern "C" int yylex(); ``` I know#definecommand but I don't understand the whole command.
It means thatYY_DECLwill be expanded to ``` extern "C" int yylex(); ``` This is actually C++, not C; when you compile this file with a C++ compiler, it declares that the functionyylexmust be compiled with "C linkage", so that C functions can call it without trouble. If you don't program in C++, this is largely irre...
I have a USB device (bicycle computer) and want to read from it values (odometer value, average speed, etc.) through the USB port. After some steps I managed to detect the computer and read some parameters (likevendorId,sessionId,deviceNameetc.), but I don't know how I can read bicycle values. There is no documentati...
You can install usbview. This is a nice and it lets you read all the descriptorshttp://www.kroah.com/linux/usb/ Another thread (USB programming) also give link ofhttp://www.signal11.us/oss/hidapi/ There are sample provided which allows read and write with the device using HID API. Hopw will help u know doing operati...
``` int a[2]; ``` This in memory actually looks like: ``` //Assuming int is 2 bytes add=2000, a[0]=124 add=2002, a[1]=534 ``` How does this actually look like in memory ``` struct l { struct l * n; long int pad[7]; }; struct l container; ``` I am unable to visualize. Please help! BT...
The layout ofstruct lwould be as follows. As the book says it will occupy 32 bytes. ``` addr ref ----------------- 2000: n 2004: pad[0] 2008: pad[1] ... 2028: pad[6] ``` On a 32-bit systemstruct l*, a pointer to a structure would occupy 4 bytes. A variable of typelong intwould occupy the sa...
I am trying to make a system call in my source code as follows. ``` int file; file = open(argv[index], O_RDONLY); ``` Where the command line arguement is a path to a binary file in my filesystem. But this call throws me anEINVALerror. I have checked the existence of file and the required permissions to access it. A...
The official documentation suggests that this is because your implementation ofopen()does not support synchronized IO for the file you are trying to open.
I created Java object and I used JAXB to convert that object into XML. Now the problem is how I can read this XML file in C? Is there any standard way or I have to use external libraries likelibxml?
Libxml2 is the "standard" way (inasmuch as there is a standard) to handle XML in C/C++. At least it has the most mindshare and best documentation and community support, AFAICT. Unless, of course, you want to write your own XML parser, which is not recommended :-)
Is there a function or any other way to calculate in C the logarithm of basex, wherexis an integer variable of my program?
C doesn't provide functions to compute logarithms of any bases other thaneor10. So just use math: ``` logarithm of x base b = log(x)/log(b) ``` If you'll be doing the logarithms over the same base repeatedly, you can precompute1/log(b).I wouldn't rely on the compiler being able to do this optimization for you.
``` struct pointsto_val_def { unsigned int lhs; bitmap rhs; struct pointsto_val_def *next; }; typedef struct pointsto_val_def *pointsto_val; typedef pointsto_val *pointsto_val_hash; ``` Can the last two statements be simply replaced by this one statement? ``` typedef struct pointsto_val_def *pointsto_va...
I think the answer is no.Because the type of pointsto_val_hash isstruct pointsto_val_def**, that means pointsto_val_hash is a pointer which is pointed tostruct pointsto_val_def*.And your replacement means a pointer which is pointed tostruct pointsto_val_def, they are not the same.
I declared a multidimensional array in C, like so: ``` int arr[4][2]; int length = 0; ``` But I can apparently add as many elements as I want: ``` void addStuff(){ arr[length][0] = someVal; arr[length++][1] = someVal; } ``` and it doesn't give any errors. Does this mean I'm corrupting my memory somewhere i...
If you assign past the array size, you're definitely corrupting memory somewhere - the program may segfault, or other data may get corrupted, or it may (by accident) behave correctly. There's no bounds checking by default in C.
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed11 years ago.Improve this question What I mean by this question is unlike other programming languages where I could simply just google the phrase "implementi...
http://www.cprogramming.com/ Also that K & R C book is available as a pdf :)
Is there any way to clear parser buffers before callingYYACCEPTinyacc. If i do not clear buffer it causes some problems when i callyyparsefor the second time. Also note that I am using some global variables, so cannot use reentrant parser. Thanks in advance !!
There sure is. Seethis sectionof the flex manual. Specifically, callYY_FLUSH_BUFFERbefore callingyyparse.
This question already has answers here:Closed11 years ago. Possible Duplicate:Post Increment and Pre Increment concept? I cant understand how the "if condition" works with the increment/decrement operator in this scenario: ``` #include<stdio.h> void main() { int n=0; if(n++) { printf("C-DAC"); } ...
if (n++)It checks ifnis not equal to zero and then incrementsn else if (n--)It checks ifnis not equal to zero and then decrementsn Your firstifstatement is not true (becausenis zero), thennis incremented, andelse ifstatement is checked (nis equal to 1 at this point),if (1)is true andprintf("ACTS")is called
I write a server using the functionchar* inet_ntoa(struct in_addr in),When I included the header<sys/socket.h>and<netinet/in.h>,an executable binary can be generated with compiler warnings, but a segment fault happens, when the program handle the return string frominet_ntoa. But when I added the header<arpa/inet.h>,ev...
arpa/inet.hcontains the declaration ofchar* inet_ntoa(struct in_addr in). If you don't include this header your compiler will use implicit declarationint inet_ntoa(). Wrong declaration can easily lead to segfault, especially if you are on system wheresizeof(int)!=sizeof(void*). If you are usinggccyou can add-Wallflag...
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
TryDoxygenworks for C (among other languages)
I've got such a function: ``` void cleanup_module(void) { /* * Unregister the device */ if(unregister_chrdev(Major, DEVICE_NAME)<0) printk(KERN_ALERT "Error in unregister_chrdev:\n"); } ``` and error: ``` /home/student/kernel/hello.c: In function ‘cleanup_module’: /home/student/kernel/h...
This means thatunregister_chrdevdoesn't have a return value (it'svoid), but you have put it in an if. That is, you are using a void value which should have been ignored. Hence the error message. Check outthis questionwhich asks why the return value was changed to void.
Will a thread stop if I send it SIGTSTP signal? Or in other words will it behave like process on SIGTSTP and SIGCONT? Thanks in advance.
From `man 3p pthread_kill: Note that pthread_kill() only causes the signal to be handled in the context of the given thread;the signal action (termination or stopping) affects the process as a whole. So I'd say that you will stop the whole process, not just the thread.
I am confused with what value should I provide for thelenparameter in theMurmurHash3_x86_128()function (and there are similar functions also). The murmurhash3 code can be foundhere. If your answer is that it is the length of the key then please explain the code at line no.154.
It is mostly certainly the length of the data to hash inbytes, the code at line 154: ``` const int nblocks = len / 16; ``` divides this length into 128bit blocks (or 16 bytes each), this is to promote faster hashing, asMurmurHash3_x86_128()processes and mixes 16 bytes (4 x uint32) per iteration. you'll notice on li...
Here is the code that doesn't work: ``` Enemy.strength = srand((unsigned)time(NULL)) % 10; ``` Enemy.strength is an int I did some research and i found you can't directly define a variable with rand/srand such as: ``` a = rand(); ``` I am just wondering why and if there is a way around this or what alternative yo...
srand(seed)returns void. It is for seeding the random number generator.rand()returns a pseudo-random integer between 0 and RAND_MAX (defined in stdlib.h). So to get a random strength for your enemy you should do something like: ``` Enemy.strength = rand() % 10; // gives a strength between 0 and 9 ``` You can place ...
After I found a file on the disk , I now need to print out all its details , for example : ``` -rwxr-xr-x 1 1000 1000 8296 2010-01-06 22:29 ./Documents/exer4 -rwxr-xr-x 1 1000 1000 8517 2009-12-30 11:30 ./Documents/os/exer4 lrwxrwxrwx 1 1000 1000 8 2010-01-10 13:10 ./Documents/cs/2012/exer4 -> ../a.out ``` I need to...
You want thestat()function. Here's a web page that documents *NIX file functions includingstat(): http://rabbit.eng.miami.edu/info/functions/unixio.html
``` TYPE *a = calloc(nelem, sizeof(TYPE)); ``` It says "unable to resolve identifier TYPE". What does this mean? Here is the code our professor gave us. We need to implement heapsort (did that in Java, and I know how it works, but I am a C virgin.)
When compiling using the code below: ``` gcc -std=c99 -DRAND -DPRNT -DTYPE={float, double} -D{BUBB, HEAP, INSR, MERG} *.c ``` You have to pick eitherfloatordouble: ``` gcc -std=c99 -DRAND -DPRNT -DTYPE=float -D{BUBB, HEAP, INSR, MERG} *.c gcc -std=c99 -DRAND -DPRNT -DTYPE=double -D{BUBB, HEAP, INSR, MERG} *.c ``` ...
Doesa && (b = 5/a)assign5/atob(for nonzeroa)? My friend says it doesn't, but I'm confused why it wouldn't.
Your friend is wrong. For nonzeroa, the statementa && (b = 5/a)will assign the value5/atob. Ifa == 0, then the conditional will short circuit and the assignment will not occur.
My program is showing "it is a leap year" for every output. Please let me know where i am committing an error?? ``` #include<stdio.h> #include<conio.h> void main() { int a; clrscr(); printf("\n Enter the year : "); scanf("%d",a); if (a%400 == 0) printf("\n It is a leap year"); else if (a%100 == 0) printf("\n It is...
Thescanf()function requires you pass theaddressof your variable: ``` scanf("%d",&a); ```
I am having a file of strings by which I want to create an enum with values named by the strings. For example the list is: ``` "a" "b" "c" "d" ... ``` I would like to get an enum like this ``` enum SomeEnum { a, b, c, d }; ``` Thanks.
You could use X-Macros, then you only need to place your enum/string in themyfile.h. myFile.h ``` #ifndef ENUM_CONVERT #define ENUM_CONVERT(val) val #define ENUM_HEADER enum SomeEnum #endif ENUM_HEADER { ENUM_CONVERT(a), ENUM_CONVERT(b), ENUM_CONVERT(c), ENUM_CONVERT(d) }; ``` myFile.c ``` #include "myFile.h" /...
I can't link properly to glew. I have done: ``` #define GLEW_STATIC #include "glew/glew.h" #pragma comment(lib, "glew/glew32s.lib") ``` However, I still get the error: LNK2019: unresolved external symbol __glewGenBuffersARB referenced in function initialize
Save yourself alotof trouble and just put theglew.cfile into your project. I never bother with linking to a glew library externally. Once you have that in there, theGLEW_STATICmacro will work. It's only one file, and (if this matters to you) it will carry nicely across platforms (rather than having to rebuild several ...
So, in my program, I have a variable ``` uint32_t buffer[16]; ``` However, there are some times where I need to treat this as ``` uint8_t char_buffer[64]; ``` The most obvious solution is a union. However, out of intellectual curiosity, is there another way to tell the compiler that I want to treat the array as an...
The casting approach is perfect. Itwillmake the compiler treat the array as an array of ints. In your particluar case, use ``` ((uint32_t *)buffer)[index]; ``` As @JerryCoffin points out, however, there's a probem with alignment. If you statically allocate the array statically as achar [], it won't necessarily be 4-...
I came across this C library:http://www.ucw.cz/libucw/It contains a sorting routine:http://www.ucw.cz/libucw/doc/sort.htmlIn array_simple.h there this function declaration: ``` static void ASORT_PREFIX(sort)(ASORT_ARRAY_ARG uns array_size ASORT_EXTRA_ARGS) ``` and further in the code: ``` struct stk { int l, r; } s...
``` typedef unsigned int uns; ``` http://www.ucw.cz/libucw/doc/def_index.html It is in ucw/config.h, which is automatically included by ucw/lib.h. (I wonder why they didn't chooseuintfor an alias instead. Although, some systems already have it as this exact type definition.)
if I do: ``` void foo() { if( .. ) { inline int baa(..) { return .. } } else { inline int baa(..) { return .. } } } ``` And call:baa(..)insidefoofunction I getimplicit declaration of 'baa'. But if I do prototype declaration:inline int baa(int);the error isinline function 'baa' declared but ...
I'm using inline function to replace macro-function. You cannotdefinefunctions inside functions, you can onlydeclarethem. Declaring them makes their names visible in that scope but those functions still need a definition somewhere, and we know we cannot define them within another function. That's why the compiler say...
Is it possible to extract the month from date represented asint(format YYYYMMDD, e.g. 20110401) using some bitwise operators? If so, how can it be done? edit: I am currently using 20110401 % 10000 / 100. I thought bit-wise could be faster. DateTime.Parse etc. are too slow for what I am trying to do.
No, because bitwise operators work with thebinaryrepresentation of the number. Your date is encoded using adecimalrepresentation. You can do it using arithmetic operators though: ``` int date = 20110401; int day = date % 100; int month = (date / 100) % 100; int year = date / 10000; ```
Someone explain why the next code returns a pointer inside ntdll.dll? ``` GetProcAddress(LoadLibraryA("kernel32.dll"), "EncodePointer"); GetProcAddress(LoadLibraryA("kernel32.dll"), "DecodePointer"); ``` PS: If call the function pointed by kernel32's export table a breakpoint is thrown.
This is a simple case ofexport forwarding, as described in one of Matt Pietrek's excellent MSDN magazine articles,An In-Depth Look into the Win32 Portable Executable File Format, Part 2. You can verify this yourself with a tool like Dependency Walker or dumpbin. ``` dumpbin /exports kernel32.dll | grep codePointer ...
How can I increase precision of variables by the Coder toolbox generated c source code? Unfortunately I have a ill-conditioned problem.
I think that unless you rely on an external library, you cannot work at higher precision than whatlong doubleallows. I'm not aware (but I could be wrong) of any ability to interface Coder to theMultiple Precision Toolboxtypes on native code. I would suggest to start from the generated C source code and then use an ar...
A fork has already occurred in code: ``` if (pid == 0) { printf("I am child PID %d\n", getpid()); exit(EXIT_SUCCESS); } else { pid_t child; int status; //need wait() function that gets child pid and exit status printf("Child PID %d terminated with return status %d\n", child, status); } ``` As...
You can usewait(), orwaitpid()(same page, really). Or, if you're on BSD,wait3(), orwait4()(but not, AFAIK,wait2()).
``` execvp(argv[1], &argv[1]) ``` What exactly is done with the second argument of execvp()?
The second argument should be a pointer to aNULL-terminated array of strings, which becomes theargvof the called process. The first element of this array becomes theargv[0]of the callee, which is not necessarily the same as its path; e.g., you can call a process by its full path, but pass it its basename asargv[0]. A...
If a struct is only used in one function, can I declare it in that function? Can I do this: ``` int func() { struct { int a, b; } s; s.a=5; return s.a; } ``` gcc choked on it, but it emitted a very weird looking error that I couldn't understand instead of saying "Sorry, you can't do that".
This is perfectly valid C89/C99/C11 code, this a structure with no tag and the object has block scope. Check C99 6.7.2.3p6 to see the identifier for the tag is optional.