question
stringlengths
25
894
answer
stringlengths
4
863
I'm writing code that uses sched_setaffinity, which requires kernel 2.5.8 or later. I've been trying to find out if these things are possible: Systems with older kernels to compile this gracefully, perhaps just ignoring that code segment entirely.If I send someone with an older kernel a compiled binary, it will step...
Usedlopen()withNULLas the filename, anddlsym()the function you want to use. If thedlsym()succeeds, call the function through the function pointer that was returned.
There is a function I have written in C that I would like to use in the debugger to send commands to a javascript engine. Since this function is not used directly in code the linker strips this symbol. Is there a way to mark a particular function to not be stripped?
Found it! http://disanji.net/iOS_Doc/#documentation/DeveloperTools/Conceptual/XcodeBuildSystem/500-Linking/bs_linking.html declaration should have ``` __attribute__((used)) ```
If the precedence of && is greater than that of ||, shouldn't this code evaluate --b && ++c first, and thus the output should be 1 2 4 11. But here it seems to be short circuited to give 1 2 5 10. Please help! ``` int x; int a=1,b=5,c=10; x=a++||--b&&++c; printf("%d %d %d %d\n",x,a,b,c); return 0; ```
shouldn't this code evaluate --b && ++c first NoOperator precedence doesn't affect evaluation order. It just means that ``` a++||--b&&++c ``` is equilvalent to ``` a++||(--b&&++c) ``` so it's stilla++that is evaluated first, and thus short-circuits the statement.
``` void echoFileA(const char* iPath,const char* oPath) { FILE* iFile; FILE* oFile; iFile = fopen(iPath,"rb"); oFile = fopen(oPath,"wb"); while(iFile) fputc(fgetc(iFile),oFile); fclose(iFile); fclose(oFile); } ``` The procedure was written purely for fun, I know that there a...
The body of your loop ... ``` fputc(fgetc(iFile),oFile); ``` ... does nothing to change the condition of the loop, so it will run forever. Instead try something like ... ``` int c; while((c = fgetc(iFile)) != EOF) fputc(c, oFile); ``` The loop will end once you hit the end of the input file.
I'm writing code that uses sched_setaffinity, which requires kernel 2.5.8 or later. I've been trying to find out if these things are possible: Systems with older kernels to compile this gracefully, perhaps just ignoring that code segment entirely.If I send someone with an older kernel a compiled binary, it will step...
Usedlopen()withNULLas the filename, anddlsym()the function you want to use. If thedlsym()succeeds, call the function through the function pointer that was returned.
There is a function I have written in C that I would like to use in the debugger to send commands to a javascript engine. Since this function is not used directly in code the linker strips this symbol. Is there a way to mark a particular function to not be stripped?
Found it! http://disanji.net/iOS_Doc/#documentation/DeveloperTools/Conceptual/XcodeBuildSystem/500-Linking/bs_linking.html declaration should have ``` __attribute__((used)) ```
If the precedence of && is greater than that of ||, shouldn't this code evaluate --b && ++c first, and thus the output should be 1 2 4 11. But here it seems to be short circuited to give 1 2 5 10. Please help! ``` int x; int a=1,b=5,c=10; x=a++||--b&&++c; printf("%d %d %d %d\n",x,a,b,c); return 0; ```
shouldn't this code evaluate --b && ++c first NoOperator precedence doesn't affect evaluation order. It just means that ``` a++||--b&&++c ``` is equilvalent to ``` a++||(--b&&++c) ``` so it's stilla++that is evaluated first, and thus short-circuits the statement.
Am trying to make while loop in my C code like this: ``` main() { char q ; while( a == 'yes' ) { /* my code */ printf("enter no to exit or yes to continue"); scanf("%s",q); } } ``` but when i input the char " q " .... the console is crashed and stop working what is my wrong in while loop ??
You can't compare a string witha == 'yes'. You need to usestrcmpfunction. You need something like this: ``` int main(int argc, char **argv) { char a[200]; strcpy(a, "yes"); while( !strcmp(a, "yes") ) { /* my code */ printf("enter no to exit or yes to continue"); scanf("%s",a); ...
I have an OpenGL program, but can't alloc correctly. ``` m_VertexData = (GLfloat*)malloc(sizeof(m_TempVertexData)); m_NormalData = (GLfloat*)malloc(sizeof(m_TempNormalData)); NSLog(@"sizeOfTempVertex: %d sizeOfTempNormal: %d", sizeof(m_TempVertexData),sizeof(m_TempNormalData)); NSLog(@"sizeOfVertex: %d sizeOfNormal: ...
sizeoftells you the size of the type (calculated at compile-time). It tells you nothing about how much memory was allocated dynamically.1 1. Except in the special case of C99's variable-length arrays.
In code example of Intel DPDK i have found this strange syntactical construction. Can anybody explain me what does it mean? ``` static const struct rte_eth_conf port_conf = { .rxmode = { .split_hdr_size = 0, .header_split = 0, .hw_ip_checksum = 0, .hw_vlan_filter = 0, .ju...
It's a C99 syntax known as adesignated initializer. In earlier C standards, the elements of a struct initializer had to appear in the same order as in the struct definition. With designated initializers, that restriction is lifted. Naturally the struct members have to be named to indicate which member is being initia...
I've defined the following struct: ``` typedef struct { double salary; } Employee; ``` I want to change the value ofsalary. I attempt to pass it by reference, but the value remains unchanged. Below is the code: ``` void raiseSalary (Employee* e, double newSalary) { Employee myEmployee = *e; myEmployee.s...
You're passing a pointer to the original,butthen you create a copy of it: ``` Employee myEmployee =*e; ``` creates a copy. ``` e->salary = newSalary; ``` will do it. Or,if you musthave an auxiliary variable for whatever reasons: ``` Employee* myEmployee =e; Myemployee->salary= newSalary; ``` This way, both varia...
I have created four sockets with different port configurations. With theselectfunction I read from one of the four file descriptors. But how can I find out on which port I received the UDP packet, I do only have the file descriptor, right? Depending on the port I need to process received packets differently. Therecv_f...
Withselectyou add all four sockets to the set you want to check, and whenselectreturns the set will contain the active sockets. You now have two ways of figuring out which specific socket/port you get back fromselect: Compare to the sockets you have.Get the local port (thoughgetsockname) and compare to the ports. I...
this code is an Integral program that calculate functions f(x) and here .. the function is f(x)= x^2 ``` int main() { float integral; float a=0,b=0; int n=1024; float h; float x; int i; float f(float x); printf("Enter a, b \n"); scanf("%f %f" , &a, &b); printf("Enter n\n"); scanf("%d" , &n); h=(b-a)/n; integr...
Here's your error:for (i = 0; i <= n-1; n++). You incrementninstead ofi.
I'm searching for afinite field/galois fieldexact linear algebra library for C (C++ is not acceptable because I need to be able to write a Haskell-binding to it and that's apparentlydifficult with C++). I found libraries for likeFFLAS-FFPACKandGivarobut these are C++-template libraries :-( In particular I want to be...
PARI/GPis opensource, is written in C and it supports some basic linear algebra over finite field. No warranties for specific suitability from me, of course - I'm not related to the development.
Here is my struct; ``` typedef struct _values { int contents[MAX_CONTENTS]; ... more ints; } values; ``` In another function, I initialize this particular array with; ``` int contents[MAX_CONTENTS] = {0}; for (i = 0; i < MAX_CONTENTS; i++) { v.contents[i] = contents[i]; } ``` And in my main I have this; ...
v(andcontentsinside of it) may be getting passed by value. Change the prototype of your function to this: ``` void newValues(values *v); ``` Change how you're calling it to this: ``` newValues(&v); ``` And rather than: ``` v.contents[i] = /* ... */; ``` Use: ``` v->contents[i] = /* ... */; ```
I have a simple program which initializes an array as: ``` int a[]={10,20,30,40,50}; char *p; p=(char*)a; ``` Now I want to access the value at each byte through pointerp. For that I need to know: how is the array stored in memory? Is it stored on the stack or the heap?
An array stores its elements in contiguous memory locations.If You created the array locally it will be on stack. Where the elements are stored depends on thestorage specification.For Example:An array declared globally or statically would have different storage specification from an array declared locally. Technically...
``` for (i = 0; i < n; i++) { x[i] = (float) (i * step); k = 5; sum = 0; while(k > 0) { sum = sum + (1/k) * sin((k*PI*x[i])/5); k = k - 2; } y1[i] = (4/PI)*sum; y2[i] = 0*(4/PI)*sin((PI*x[i])/5); } ``` When debugging for ...
Since both 1 and k are ints -- 1/k isinteger division, its always going to be 0 if k > 1. Therefore nothing is added to sum. You want 1/k to perform floating point division. Try1.0 / kinstead of 1/k.
Namely code similar to this, making the printout undefined. ``` int a=41; a++ & printf("%d\n", a); ``` I don't know what exactly this operation is called.
The problem is that it is not specified which is evaluated first, theprintfor thea++, and since one has a side effect on the other (you either readathen write it then read it again, or read it then read it then write it), you get undefined behaviour.
I want to recursively copy one directory into another (likecp -R) using POSIXscandir(). The problem is that when I copy a directory like /sys/bus/, which contains links to higher levels (for example: foo/foo1/foo2/foo/foo1/foo2/foo/... ) the system enters a loop status and copies the directories "in the middle" forev...
Look at this:How to check whether two file names point to the same physical file You need to store a list of inodes that you have visited to make sure that you don't get any duplicates. If you have two hard links to the same file, there is no "one" canonical name. One possibility is to first store all the files and...
I need an array of strings. The length of a string is known at compile-time and it is crucial that each string takes up this much space. The number of strings on the other hand is only known at runtime. What is the syntax for this? char* data[STRLENGTH]is incorrect syntax.char** datamostly works but thensizeof(data[0...
@Daniel is correct, but this code can confuse people who read it - it's not something you usually do. To make it more understandable, I suggest you do it in two steps: ``` typedef char fixed_string[STRLENGTH]; fixed_string *data; ```
Here is my struct; ``` typedef struct _values { int contents[MAX_CONTENTS]; ... more ints; } values; ``` In another function, I initialize this particular array with; ``` int contents[MAX_CONTENTS] = {0}; for (i = 0; i < MAX_CONTENTS; i++) { v.contents[i] = contents[i]; } ``` And in my main I have this; ...
v(andcontentsinside of it) may be getting passed by value. Change the prototype of your function to this: ``` void newValues(values *v); ``` Change how you're calling it to this: ``` newValues(&v); ``` And rather than: ``` v.contents[i] = /* ... */; ``` Use: ``` v->contents[i] = /* ... */; ```
I have a simple program which initializes an array as: ``` int a[]={10,20,30,40,50}; char *p; p=(char*)a; ``` Now I want to access the value at each byte through pointerp. For that I need to know: how is the array stored in memory? Is it stored on the stack or the heap?
An array stores its elements in contiguous memory locations.If You created the array locally it will be on stack. Where the elements are stored depends on thestorage specification.For Example:An array declared globally or statically would have different storage specification from an array declared locally. Technically...
``` for (i = 0; i < n; i++) { x[i] = (float) (i * step); k = 5; sum = 0; while(k > 0) { sum = sum + (1/k) * sin((k*PI*x[i])/5); k = k - 2; } y1[i] = (4/PI)*sum; y2[i] = 0*(4/PI)*sin((PI*x[i])/5); } ``` When debugging for ...
Since both 1 and k are ints -- 1/k isinteger division, its always going to be 0 if k > 1. Therefore nothing is added to sum. You want 1/k to perform floating point division. Try1.0 / kinstead of 1/k.
Namely code similar to this, making the printout undefined. ``` int a=41; a++ & printf("%d\n", a); ``` I don't know what exactly this operation is called.
The problem is that it is not specified which is evaluated first, theprintfor thea++, and since one has a side effect on the other (you either readathen write it then read it again, or read it then read it then write it), you get undefined behaviour.
I want to recursively copy one directory into another (likecp -R) using POSIXscandir(). The problem is that when I copy a directory like /sys/bus/, which contains links to higher levels (for example: foo/foo1/foo2/foo/foo1/foo2/foo/... ) the system enters a loop status and copies the directories "in the middle" forev...
Look at this:How to check whether two file names point to the same physical file You need to store a list of inodes that you have visited to make sure that you don't get any duplicates. If you have two hard links to the same file, there is no "one" canonical name. One possibility is to first store all the files and...
I need an array of strings. The length of a string is known at compile-time and it is crucial that each string takes up this much space. The number of strings on the other hand is only known at runtime. What is the syntax for this? char* data[STRLENGTH]is incorrect syntax.char** datamostly works but thensizeof(data[0...
@Daniel is correct, but this code can confuse people who read it - it's not something you usually do. To make it more understandable, I suggest you do it in two steps: ``` typedef char fixed_string[STRLENGTH]; fixed_string *data; ```
Here is my struct; ``` typedef struct _values { int contents[MAX_CONTENTS]; ... more ints; } values; ``` In another function, I initialize this particular array with; ``` int contents[MAX_CONTENTS] = {0}; for (i = 0; i < MAX_CONTENTS; i++) { v.contents[i] = contents[i]; } ``` And in my main I have this; ...
v(andcontentsinside of it) may be getting passed by value. Change the prototype of your function to this: ``` void newValues(values *v); ``` Change how you're calling it to this: ``` newValues(&v); ``` And rather than: ``` v.contents[i] = /* ... */; ``` Use: ``` v->contents[i] = /* ... */; ```
I have a simple program which initializes an array as: ``` int a[]={10,20,30,40,50}; char *p; p=(char*)a; ``` Now I want to access the value at each byte through pointerp. For that I need to know: how is the array stored in memory? Is it stored on the stack or the heap?
An array stores its elements in contiguous memory locations.If You created the array locally it will be on stack. Where the elements are stored depends on thestorage specification.For Example:An array declared globally or statically would have different storage specification from an array declared locally. Technically...
``` for (i = 0; i < n; i++) { x[i] = (float) (i * step); k = 5; sum = 0; while(k > 0) { sum = sum + (1/k) * sin((k*PI*x[i])/5); k = k - 2; } y1[i] = (4/PI)*sum; y2[i] = 0*(4/PI)*sin((PI*x[i])/5); } ``` When debugging for ...
Since both 1 and k are ints -- 1/k isinteger division, its always going to be 0 if k > 1. Therefore nothing is added to sum. You want 1/k to perform floating point division. Try1.0 / kinstead of 1/k.
Namely code similar to this, making the printout undefined. ``` int a=41; a++ & printf("%d\n", a); ``` I don't know what exactly this operation is called.
The problem is that it is not specified which is evaluated first, theprintfor thea++, and since one has a side effect on the other (you either readathen write it then read it again, or read it then read it then write it), you get undefined behaviour.
I want to recursively copy one directory into another (likecp -R) using POSIXscandir(). The problem is that when I copy a directory like /sys/bus/, which contains links to higher levels (for example: foo/foo1/foo2/foo/foo1/foo2/foo/... ) the system enters a loop status and copies the directories "in the middle" forev...
Look at this:How to check whether two file names point to the same physical file You need to store a list of inodes that you have visited to make sure that you don't get any duplicates. If you have two hard links to the same file, there is no "one" canonical name. One possibility is to first store all the files and...
I need an array of strings. The length of a string is known at compile-time and it is crucial that each string takes up this much space. The number of strings on the other hand is only known at runtime. What is the syntax for this? char* data[STRLENGTH]is incorrect syntax.char** datamostly works but thensizeof(data[0...
@Daniel is correct, but this code can confuse people who read it - it's not something you usually do. To make it more understandable, I suggest you do it in two steps: ``` typedef char fixed_string[STRLENGTH]; fixed_string *data; ```
This question already has answers here:Closed11 years ago. Possible Duplicate:How to get the value of individual bytes of a variable? How can I get single bytes from a word (for example anunsigned intin C) without using bit-wise operations (that is using arithmetic operations?) I don't know why, but this formula (C...
If you really need to avoid bitwise operations, you can cheat alternatively (beware if you're using a little or big endian machine!): ``` char *int_16_storage; uint16_t the_word = 0xabcd; int_16_storage = &the_word; uint8_t low_byte = int_16_storage[0]; uint8_t high_byte = int_16_storage[1]; ```
I'd like to know which one of the following two forms of lazy instantiation generates faster assembly code. Here's the code: 1st: ``` if (!_separatorTopBorderColor) _separatorTopBorderColor = UIColorFromHex(0x393A3B); return _separatorTopBorderColor; ``` 2nd: ``` _separatorTopBorderColor = _separatorTopBorderColor...
It might be an issue 10 years ago, but nowadays, compilers literally sees any difference withternaryoperators andif-elsestatements. My advise is that you should concentrate on keeping your code more readable, maintainable, and efficient. Don't care about resource or memory usage in this case.
I am currently working on moving some bash scripts over to C, and one of them call's an external python script, so for instance ./remoteclient01a.py "remotecommand player /something something" ``` ./remoteclient01a.py "remotecommand player /something something" ``` and Ive been looking for a way to execute this comm...
The only portable ways to do this in C aresystemandpopen. The functionpopenallows you to read output from the command.
This question already has answers here:Closed11 years ago. Possible Duplicate:Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…) I have heard that printf function executes from right to left and prints from left to right. By that convention, the following program should give 7,6,5. But it...
The evaluation order in your code is undefined, as there are no sequence points. You cannot relay on the evaluation order of function arguments, and you cannot change it either. Checkhttp://www2.research.att.com/~bs/bs_faq2.html#evaluation-order
It just confused me: typedef bool(*pGetNameByPid)(DWORD PID, TCHAR lpszProcessName[MAX_PATH]); Is there anything with the sentence above? I want to export an function namedGetNameByPidfrom an DLL written in C++. But the compile reports that: error C2143: syntax error : missing ')' before '*' Any help?
There is nobooltype in C89, which is the C standard that the Microsoft Compilers support. You could use anintor WINAPI'sBOOLas the return type: ``` typedef BOOL (*pGetNameByPid)(DWORD PID, TCHAR lpszProcessName[MAX_PATH]); ``` To export a function from DLL: ``` __declspec(dllexport) BOOL GetNameByPid(DWORD PID, TCH...
I'm using PyGObject but I think this is a question that could be adapted to all GTK, so if someone know how to do it using C or anything should work in python also. I have two treeview, Active and Inactive, I load data from a Sqlite database and I can swap and drag & drop items from one to other. This is just an aes...
At the risk of being too basic (perhaps I misunderstand the problem), to manipulate treeview selections, you use theGtkTreeSelectionobject returned fromGtkTreeView.get_selection. You can attach to signals on this object, change the current selection,etc.
Ok, I am a bit embarrassed to ask such a simple thing but still. I have command line utility application and need to show progress to the user. I could write progress into cout, like this: ``` std::cout << "10%\n"; ... std::cout << "20%\n"; ... std::cout << "30%\n"; ``` ... but as a result user will see: ``` some...
Instead of using'\n', use'\r': ``` std::cout << "\r10%" << std::flush; ``` Print newline ('\n') when done. It's important to usestd::flushso the stream contents really is output.
Which of the following techniques is the best option for dividing an integer by 2 and why? Technique 1: ``` x = x >> 1; ``` Technique 2: ``` x = x / 2; ``` Herexis an integer.
Use the operation that best describes what you are trying to do. If you are treating the number as a sequence of bits, use bitshift.If you are treating it as a numerical value, use division. Note that they are not exactly equivalent. They can give different results for negative integers. For example: ``` -5 / 2 = ...
I have header file with the following function declaration: ``` extern getEmailDetailsResult * getemaildetails_5(getEmailDetailsInput *, CLIENT *); ``` In my .C file, the function definition is ``` getEmailDetailsResult* getemaildetails_5(inputParams, rqstp) getEmailDetailsInput *inputParams; struct svc_re...
It looks like thestruct svc_req *pointer is not equivalent to theCLIENT *pointer.
I have compiled my ownglibc, which producedlibc.so. I loaded thelibc.sofile in gdb by doinggdb -q ./libc.so. However, when I try to find the location of a function by doinglist function_name, I get the error message,No line number known for function_name. Note that I use the -g flag for compilingglibc. How can I solve...
Can you even debug a .so by itself? What I would try is to do isgdb executable_using_my_libc. Then this should load glibc and so on.
How can I increase the mesh size of Comsol without increasing the memory of my system? My system memory is 32 GB but I cannot simulate my problem because it needs a lot of memory. How can I solve this problem?
Increase the mesh size. Increasing the mesh size cause decreasing the amount of memory that is needed for simulation. With increasing the mesh size you can solve huge problems with less memory. There is no other way for decreasing the amount of memory that you need for simulation; because you don't write any program a...
I got some images to download using HTTP. I got these images' URL, how to build the TCP-based HTTP buffer to download the image? I got no library in my current platform, the only supported language in this platform is C, so I have to build the HTTP buffer for these resources. Currently I have build the normal API re...
You would have to implement HTTP protocol or a subset of it. There are open source implementations. For example: https://github.com/bagder/curl/tree/master/lib https://github.com/joshthecoder/libhttp
``` Write a program that reads an decimal number between 0 and 2G and displays the 32-bit binary version on the video display ``` Someone ask me that question, ok 0 is 0 but I need EXPLAIN here what does"2G"mean and what is"32-bit binary version on the video display"any difference with normal 32-bit binary(32 number...
From what I can determine, 2G is the maximum representable 32-bit signed value, aka 2147483647, expressed as 0 followed by 31 1's. 32-bit binary version on the video display" any difference with normal 32-bit binary(32 number 1 and 0)? No difference as best I can tell.
I am trying to figure out a way to count the amount of specific file in a directory, lets say for instance I have a directory with ``` hi-austin.txt goodbye-austin.txt cya-austin.txt hey-austin.txt ``` and I wanted to count the amount of files that fit this specification, *-austin.txt, normally I would use the bash ...
You could use: opendir()andreaddir()to access the file names in a current directoryto check if a filename ends with a particular string:int ends_with(const char* const a_str, const char* const a_search_str) { const size_t str_len = strlen(a_str); const size_t search_len = strlen(a_search_str)...
How does the following code compile correctly, ``` #include <stdio.h> #define stringer( x ) printf_s( #x "\n" ) int main() { stringer( "In quotes when printed to the screen" ); } ``` isn't it supposed to get expanded into ``` printf_s(""In quotes when printed to the screen""\n"); ``` which is an error as there ...
No, the#operator handles character string literals specially. It must\escape each"in a character string literal that is passed to it. The correct expansion is: ``` printf_s( "\"In quotes when printed to the screen\"" "\n" ); ```
How does the TEXT("x") macro expand to L"x" if unicode is defined and "x" if unicode is not defined because when I try to compile the following code it says "error #1049: Syntax error in macro parameters." ``` #define T("x") "x" int main() { } ```
Lookup thetchar.hheader in your installation. You'd get something like the following: ``` #define __T(x) L ## x ``` In Unicode mode, the above macro pastes anLand a string argument together. In ASCII mode, there is no prefix to paste so it goes simply as: ``` #define __T(x) x ``` Note that you invoke thi...
I found the solution myself: refreshwinafterstdscr. I would like to have a white window in a blue screen, and I tried it with the following code: ``` initscr(); WINDOW *win = newwin(10, 10, 10, 10); start_color(); init_pair(1, COLOR_BLACK, COLOR_BLUE); init_pair(2, COLOR_BLACK, COLOR_WHITE); wbkgd(stdscr, COLOR...
Solution: Refresh the window afterstdscr: ``` refresh(); wrefresh(win); ``` instead of: ``` wrefresh(win); refresh(); ```
I'm writing a GUI to an application, but the main developer wants to set in Makefile if the GUI get or not compiled with the rest. I'm putting all the GTK+ code in a separated file, but in the main file I need to test if the application is being compiled with the GUI or not, so how I can test this? E.g: ``` if(COMPI...
Assuming thatCOMPILED_WITH_GTKis an argument to the compiler command in the Makefile (in the form of-DCOMPILED_WITH_GTK) you use a preprocessor directive. ``` #ifdef COMPILED_WITH_GTK #include "my_gtk_stuffs.h" #endif ``` This tells the preprocessor to only process the#includestatement ifCOMPILED_WITH_GTKis defined....
I'm looking for a cross-platform(works at UNIX-like and Windows) library to handling operating system date. Is there it for C programmers? or C++ if really have no for C. Thanks in advance!
Perhaps you should tryBoost.Date_Time.
I'm injecting a DLL into another process and want to call a function that is in that binary based on it's address (0x54315). How can I actually declare a function, and then set it to this address? ``` #define FUNC 0x54315 void *myFuncPtr; int main() { myFuncPtr = FUNC; // pretty sure this isn't how myFuncPtr()...
The existing answers work, but you don't even need a variable for the function pointer. You can just do: ``` #define myfunc ((void (*)(void))0x54315) ``` and then call it asmyfunc()just like you would an ordinary function. Note that you should change the type in the cast to match the actual argument and return types...
I am pretty new to C and I have got a problem here in C: I want to write a program which reads a txt file and writes the content it achar[50][50]. To read the file I usedfopenbut I have no idea how to write this into the array. What is a good way to solve this?
Easy to use fread if it only read from a file the size of the specific.E.g. ``` #include <stdio.h> #include <stdlib.h> int main() { FILE *fp; char data[50][50]; int count; if(NULL==(fp=fopen("data.txt","r"))){ perror("file not open\n"); exit(EXIT_FAILURE); } count=fread(&data...
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...
cython is what you are looking forhttp://www.cython.org/
I wrote this function to join two paths in C; ``` void *xmalloc(size_t size) { void *p = malloc(size); if (p == NULL) { perror("malloc"); exit(EXIT_FAILURE); } return p; } char *joinpath(char *head, char *tail) { size_t headlen = strlen(head); size_t taillen = strlen(tail); ...
while (tmp1 != NULL)is incorrect.Should bewhile (*tmp1 != '\0').The pointer itself never becomes NULL. Just what it points to.
What is the difference between these two function pointer notations in C? void (*a[]())andvoid (*a)()[] Do they both represent same - a as an array of pointers to functions - or does the second one represent a pointer to an array of functions? How should I call these functions - sayvoid (*a[]()) = {swap, add, sub,...
Usecdecl.orgto figure this stuff out until you can do it without thinking about it. void (*a[]()): declare a as array of function returning pointer to void whereas void (*a)()[]: declare a as pointer to function returning array of void The latter is invalid C.
A character array is defined globally and a structure with same name is defined within a function. Why sizeof operator returns different values for c & c++ ? ``` char S[13]; void fun() { struct S { int v; }; int v1 = sizeof(S); } ``` // returns 4 in C++ and 13 in C
Because in C++, thestructyou defined is namedS, while in C, it's namedstruct S(which is why you often seetypedef structused in C code). If you were to change the code to the following, you would get the expected results: ``` char S[13]; void fun() { typedef struct tagS { int v; } S; int v1 = s...
In eclipse, how do I tell the console to submit the text? When I press enter, it just goes to a new line where I can continue typing and does not submit the text to continue processing.
To heck with eclipse.. I found a way of getting Visual Studio to compile C++ projects as C projects.. much better... after spending so many hours trying to get the IDE working with all its quirks... I don't think I'll be going back to that again (at least not for anything C anyway). For anyone interested:http://www.d...
I created a Combobox withCreateWindowEx. Everything goes well. But I would like to make a final feature: AutoSuggestion. The Combobox is used to do search text in a document, hence at some point, it have items that are the strings a user searched. The AutoSuggestion should be: drop down the list of items, find those i...
It sounds like you wantAutocomplete functionality.
Is there a method to keep fwrite from blocking, like say using timeouts? The scenario is this: I need to make a fwrite call (since I am largely reusing a code , I need to stick to it) on a network. However if I pull off the network cable, the fwrite blocks. Is there a workaround? Any help/suggestions will be greatly ...
Switch an underlying file descriptor to non-blocking mode: ``` int fd = fdnum(stream); int f = fcntl(fd, F_GETFL, 0); f |= O_NONBLOCK; fcntl(fd, F_SETFL, f); ``` After this a call tofwrite()will immediately return and seterrnoto EAGAIN if the file descriptor is not ready for being written to. Calling it in a loop an...
This question already has answers here:Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer(5 answers)Closed7 years ago. Why does the following code return with a segmentation fault? When I comment out line 7, the seg fault disappears. ``` int main(void){ char *s; in...
sis an uninitialized pointer; you are writing to a random location in memory. This will invokeundefined behaviour. You need to allocate some memory fors. Also,never usegets; there is no way to prevent it overflowing the memory you allocate. Usefgetsinstead.
ThecreateFileAtPath:contents:attributesfor Objective-C:contentsrequires anNSDatatype, but I want to create a file with aNSStringcontent. How do I do this? I know it's probably a really basic answer, but I'm just starting to learn how to use Objective-C, and it has so many different data types and objects compared to ...
You can try creatingNSDatawith the content of the string, like this: ``` NSString *s = @"Hello, world!"; NSData *d = [s dataUsingEncoding:NSUTF8StringEncoding]; ``` You can also store anNSStrngto a file directly: ``` [s writeToFile:@"/my/file/path/file.txt" atomically:NO encoding:NSUTF8StringEncoding error:nil]; ``...
I am writing some C code here, and I came across a problem: I have an array of my custom type. I want to put a size for this array: ``` typedef struct reg Reg; Reg myArray[958279]; ``` When I run my program has a segmentation fault. Then I tried using malloc, which allocates storage space dynamically, and to my su...
The array in your first piece of code is, presumably, being allocated on the stack and does not fit. The stack typically has a fixed size and you must not allocate huge objects on the stack. The solution, as you have discovered, is to allocate from the heap.
I want to make a function pointer array and be able to call them in a for-loop. How can I achieve this? I have tried: ``` void (**a) (int); a[0] = &my_func1; a[1] = &my_func2; a[2] = &my_func3; for ( i = 0; i < 3; i++){ a[0](); (*a[0])(); // Neither does work } ``` But I am missing some syntax I guess: ```...
The function you declare is expected to take an int as a parameter: ``` a[0](1); ``` Also note that you declare a pointer to pointer for the functions, but you don't allocate any memory for them (I assume this is only in the example) Otherwise it should probably be: ``` void (*a[3]) (int); ```
I have this struct ``` typedef struct { int numberPipes; // | int numberAmpersands; // & int existsBiggerThan; // > int existsLessThan; // < int existsDoubleLargerThan; // >> } lineData; ``` and I run in my loop on achararray (char*), in order to find all...
You can do that by callingrealloc. For performance reasons, it might be better to call it not for each new element, but once in X elements, so you reduce the number of calls tomalloc/realloc.
I am trying to write a C code that will find hyperlinks in a mail and replace them. Is using a pcre library a good thing to do ? Since pcre is ,allegedly, too slow is there an alternative ?
C is thelastlanguage I would choose to do this. Firstly, if you want to do this with high accuracy - use a MIME parser to get the HTML body out. Java has mime4j, Perl has MIME::Parser, Python has email, etc. This isn't too hard and I'm willing to help with this step in any of these languages if you'd like. Secondl...
Here is part of my code. I would like to initialize only thearraylist[0]asarraylist[0].x = 0andarraylist[0].y = 0. I do not need to initialize the rest of the struct array. How can I do it? Thank you. ``` #include <stdio.h> struct example { int x; int y; }; struct example arraylist[40]; int main(int argc, ch...
You can initialise any particular element of the struct array. For example: ``` struct example arraylist[40] = { [0]={0,0}}; //sets 0th element of struct struct example arraylist[40] = { [5]={0,0}}; //sets 6th element of struct ``` This is calledDesignated Initializerswhich used to be a GNU extension before C99 ad...
please find thecodefor the service created to detect my USB device. The problem in the above code is that the logfile is getting updated only after the service is stopped. My intension is to update the log file once the device is detected.. But it happens only after the service is stopped. how to achieve what i inte...
To avoid losing log entries, you need to flush thefwrites . fflush(your file handle )
This question already has answers here:Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer(5 answers)Closed7 years ago. Why does the following code return with a segmentation fault? When I comment out line 7, the seg fault disappears. ``` int main(void){ char *s; in...
sis an uninitialized pointer; you are writing to a random location in memory. This will invokeundefined behaviour. You need to allocate some memory fors. Also,never usegets; there is no way to prevent it overflowing the memory you allocate. Usefgetsinstead.
ThecreateFileAtPath:contents:attributesfor Objective-C:contentsrequires anNSDatatype, but I want to create a file with aNSStringcontent. How do I do this? I know it's probably a really basic answer, but I'm just starting to learn how to use Objective-C, and it has so many different data types and objects compared to ...
You can try creatingNSDatawith the content of the string, like this: ``` NSString *s = @"Hello, world!"; NSData *d = [s dataUsingEncoding:NSUTF8StringEncoding]; ``` You can also store anNSStrngto a file directly: ``` [s writeToFile:@"/my/file/path/file.txt" atomically:NO encoding:NSUTF8StringEncoding error:nil]; ``...
I am writing some C code here, and I came across a problem: I have an array of my custom type. I want to put a size for this array: ``` typedef struct reg Reg; Reg myArray[958279]; ``` When I run my program has a segmentation fault. Then I tried using malloc, which allocates storage space dynamically, and to my su...
The array in your first piece of code is, presumably, being allocated on the stack and does not fit. The stack typically has a fixed size and you must not allocate huge objects on the stack. The solution, as you have discovered, is to allocate from the heap.
I want to make a function pointer array and be able to call them in a for-loop. How can I achieve this? I have tried: ``` void (**a) (int); a[0] = &my_func1; a[1] = &my_func2; a[2] = &my_func3; for ( i = 0; i < 3; i++){ a[0](); (*a[0])(); // Neither does work } ``` But I am missing some syntax I guess: ```...
The function you declare is expected to take an int as a parameter: ``` a[0](1); ``` Also note that you declare a pointer to pointer for the functions, but you don't allocate any memory for them (I assume this is only in the example) Otherwise it should probably be: ``` void (*a[3]) (int); ```
I have this struct ``` typedef struct { int numberPipes; // | int numberAmpersands; // & int existsBiggerThan; // > int existsLessThan; // < int existsDoubleLargerThan; // >> } lineData; ``` and I run in my loop on achararray (char*), in order to find all...
You can do that by callingrealloc. For performance reasons, it might be better to call it not for each new element, but once in X elements, so you reduce the number of calls tomalloc/realloc.
I am trying to write a C code that will find hyperlinks in a mail and replace them. Is using a pcre library a good thing to do ? Since pcre is ,allegedly, too slow is there an alternative ?
C is thelastlanguage I would choose to do this. Firstly, if you want to do this with high accuracy - use a MIME parser to get the HTML body out. Java has mime4j, Perl has MIME::Parser, Python has email, etc. This isn't too hard and I'm willing to help with this step in any of these languages if you'd like. Secondl...
Here is part of my code. I would like to initialize only thearraylist[0]asarraylist[0].x = 0andarraylist[0].y = 0. I do not need to initialize the rest of the struct array. How can I do it? Thank you. ``` #include <stdio.h> struct example { int x; int y; }; struct example arraylist[40]; int main(int argc, ch...
You can initialise any particular element of the struct array. For example: ``` struct example arraylist[40] = { [0]={0,0}}; //sets 0th element of struct struct example arraylist[40] = { [5]={0,0}}; //sets 6th element of struct ``` This is calledDesignated Initializerswhich used to be a GNU extension before C99 ad...
please find thecodefor the service created to detect my USB device. The problem in the above code is that the logfile is getting updated only after the service is stopped. My intension is to update the log file once the device is detected.. But it happens only after the service is stopped. how to achieve what i inte...
To avoid losing log entries, you need to flush thefwrites . fflush(your file handle )
I used the below linkhttp://www.muukka.net/programming/service/Beeper%20Service.cppto write a service. but the problem here is, the servicemain function gets called only when service stop is requested. I want to start the servicemain function before hand, to detect usb devices connected.. what should I do for that..
In code: SC_HANDLE service = CreateService( serviceControlManager, serviceName, serviceName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, path, 0, 0, 0, 0, 0 ); change to: SC_HANDLE service = CreateService( serviceControlManager, serviceName, serviceName, SERVICE_ALL_A...
I get this error when I'm trying to malloc some memory for my struct of ints. ``` typedef struct _values { random ints; } values; ``` I have tried the lines below but my compiler doesn't like it. How do I fix the error? ``` values v; v = malloc(sizeof(values)); ```
You forgot to add the asterisk (*) after thevaluesand before thevto mark it as a pointer:values *v; The way you set it now, the v (without the asterisk) is defined as a stack variable and would be allocated on the stack and discarded once the function ends. It's type will be simplyvalues.mallocis used to allocate mem...
What does this macro do? I am not able to understand its definition: ``` #define PAIR(def) [def] = { .name = #def, .val = def, }, ``` From : ltp-full-20120401/lib/tst_res.c line 183 You can get the source from thislink
It looks like it is used to initialize an array of structs. ``` #define PAIR(def) [def] = { .name = #def, .val = def, }, ``` the macro used as followsPAIR(FOOBAR)would expand to: ``` [FOOBAR] = { .name = "FOOBAR", .val = FOOBAR, }, ``` .nameand.valwould be members of thestructtype of the array elements.
On SMP machines is there a performance benefit to #2 vs #1: 1) x = 0; or 2) if (x) x = 0; I was thinking that the behind the scenes overhead to manage cache coherency between the CPUs might have some cost. Am I nuts?
Even with single-threaded code, the latter can have an advantage if the object lies in copy-on-write memory (for example, a private mapping of a file, or almost any writable memory after a fork). I suspect the advantage you're asking about is real too, at least on systems like x86 where memory consistency is handled a...
Can someone please explain me why its not possible to put a'\0'character in the given array: ``` char a[]={'r','b'}; a[2]='\0'; ``` Shouldn't the above code put a null character at the third slot and hence convert the character array a to a character string.
You are writing past the array boundary: when you initialize an array with two characters, the last valid index is1, not2. You should initialize your array with three items, as follows: ``` char a[] = {'r', 'b', '\0'}; ``` You could as well use this version: ``` char a[] = "rb"; ``` This will give you awritablear...
This question already has answers here:Closed11 years ago. Possible Duplicate:Why was the switch statement designed to need a break? I have this: ``` switch(i) { case a: { //code } case b: { //code } case c: { //code } } ``` Ifi == a, will the code inbandcbe executed or must I put abreak...
Must I put abreak;in each one? Yes, if you only want a single case to execute. Alternatively, other control flow statements can also cause aswitchto be exited, likereturnorthrow. If you were to replace//codewith, say,std::cout << "case [x]" << std::endl, the answer would be readily apparent.
A coworker of mine was looking through one of our inherited code bases and found the following line: ATLASSERT( rtaddress == m_lRTAddress && "Creation settings should match FIFO" ); We don't understand what the purpose of the string literal is for; is it for more than just commenting? The way I see it, ifrtaddressd...
I think it's so that if the assert fails you can see the reason why the assert was added.
I am working with a C Framework in MacRuby which has a structure ``` int CPhidget_getSerialNumber(CPhidgetHandle phid,int * serialNumber) ``` You can see the full documentationhere(if you are interested). In MacRuby I have tried the following: ``` i = CPhidget_getSerialNumber(@encoder, nil) ``` The above gets me ...
MacRuby has a Pointer class, which can stand in for a C pointer. So, you could do something like: ``` i = Pointer.new(:int) CPhidget_getSerialNumber(@encoder, i) ``` Then, to extract the results from the pointer (i.e. dereference it), you use Ruby's array access syntax: ``` i[0] #=> value from CPhidget_getSerialNum...
Hi I am a c programmer but I've never programmed for networks before. I would like to write a program in c or c++ for Linux that will be able to verify the latency of access point and packet loss. I was thinking that maybe ICMP request/respond (ping) would be not too bad idea? If above idea is good how this could be ...
For linux, you could make a program to parse the/proc/net/wirelessfile. Let the kernel get the information for you.iwconfiggets information from there (http://linux.die.net/man/8/iwconfig)
I have a functiongetData(void* data)which should copy to data some internal calculated values for exampleint r = getRadius();r should be copied to data ,and is such a way returned from function getData what is the correct way to do it? I tried*(int*)data = r;but I am not sure this is a best solution.
If you are certain that the memory referenced by the void pointer is an int, then you can be confident in ``` *(int *)data = r; ``` However a better general solution is: ``` memcpy(data, &r, sizeof(int)); ``` This way you don't have to worry about byte alignment or other potential gotchas.
I'm trying to compare an integer and a double: ``` printf("%d\n", pos<(td+tr)); if(td <= pos < (td+tr)) {} ``` The print statement evaluates the comparisonpos<(td+tr)properly. Theif(td <= pos < (td+tr))comparison does not evaluate properly. Pos is an int:int pos;td and tr are doubles:double ...
``` td <= pos < (td+tr) ``` is evaluated left to right. So first ``` td <= pos ``` is evaluated to a truth value. And then that truth value is compared withtd+tr. That's not what you want. You want ``` if (td <= pos && pos < td+tr) ```
So I have a CMTime from a video. How do I convert it into a nice string like in the video time duration label in the Photo App. Is there some convenience methods that handle this? Thanks. ``` AVURLAsset* videoAsset = [AVURLAsset URLAssetWithURL:url options:nil]; CMTime videoDuration = videoAsset.duration; float video...
You can use this as well to get a video duration in a text format if you dont require a date format ``` AVURLAsset *videoAVURLAsset = [AVURLAsset assetWithURL:url]; CMTime durationV = videoAVURLAsset.duration; NSUInteger dTotalSeconds = CMTimeGetSeconds(durationV); NSUInteger dHours = floor(dTotalSeconds / 3600); N...
Does calloc allocate return contiguous memory location? If yes, what would it do if it is not available?
Does calloc allocate returns contiguous memory location? Yes.1 what would it do if it is not available? ReturnNULL. See section 7.20.3.1 of the C99 standard. 1. So far as the C program is concerned. In a virtual memory system, the underlying physical memory used may not be contiguous.
I'm getting a very strange error while trying to read from a simple text file with c fread() call.I made a very simple program to show that error: ``` int main(int argc ,char ** argv) { FILE* fh = fopen("adult.txt","r"); if(fh==NULL){ printf("error opening file\n"); exit(0); } int s = 1000; printf(...
That's normal. '\n'can be represented with two characters, so there is the skew you are getting. If you don't want that to happen, open the finaly in binary mode.
I am new using libcurl. I am not understanding clearly how to use it for HTTP POST requests and how to check the result. How can I use it for this?
``` #include <curl/curl.h> main() { CURL *curl; curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); curl_easy_setopt(curl, CURLOPT_URL, "http://www.example.com/hello-world"); curl_easy_setopt(curl, CURLOPT_POST, 1); curl_easy_setopt(curl, CURLOPT_POSTFI...
I was making some proves with strtol() from stdlib library because i had a program that always crashed and i found that this worked perfectly: ``` main(){ char linea[]="0x123456",**ap; int num; num=strtol(linea,ap,0); printf("%d\n%s",num,*ap); } ``` But when I added just a new declaration no matter where it crashed ...
You get a crash because you are passingstrtolan uninitialized pointer, andstrtoldereferences it. You do not get a crash the first time by pure luck. This will not crash: ``` main() { char linea[]="0x123456", *ap; int num; num = strtol(linea, &ap, 0); printf("%d\n%s", num, ap); int k; } ```
In my function, I first use mod as below: ``` void function(int, int, unsigned int); ``` calling: ``` function(100, 200, get_value() % 1024); ``` Theget_value()will return a unsigned int that varies from0x0 to0xffffffff. In this situationget_value() % 1024may be a very big number larger than1024that causesfunction...
Your prototype is forfunction, but you are callingfunction1. In this case, thefunction1function has no prototype, so the last parameter is considered to be anint. That's why you do not get the expected conversion. Renaming the prototype should fix it: ``` void function1(int, int, unsigned int); ```
What is the reason for this? I thought that if a pointer is null then the rest of the condition won't be evaluated. ``` // doesn't work: char *ptr = somefunction(); if (ptr && ptr[0] == '1' || ptr[0] == 't') // ... // does work: char *ptr = somefunction(); if (ptr) if (ptr[0] == '1' || ptr[0] == 't') ...
``` ptr && ptr[0] == '1' || ptr[0] == 't' ``` means: ifptr && ptr[0] == '1'(false, becauseptris null andptr[0] == '1'doesn't get evaluated)orptr[0] == 't'(boom) Use: ``` ptr && (ptr[0] == '1' || ptr[0] == 't') ``` instead.
I'm reading through some code for an Arduino example and I came across this line: uint16_t pulses[100][2]; It appears that this is defining a 100x2 array -- is that correct?
You are correct. It defines a 100x2 array of unsigned 16 bit integers.
I have a typedef in anifmacro, something like: ``` #ifdef BLA_BLA typedef int typeA #elseif typedef double tyeA #endif printf("%d" , a); printf("%l" , a); ``` I am wondering what is the best approach when I write a printf for this case? (%dor%l). I know I can define a fixed string in the macro as well. But is it t...
Use a macro to define the format string too. ``` #ifdef BLA_BLA typedef int typeA; #define FORMAT "%d" #elseif typedef double typeA; #define FORMAT "%f" #endif ... typeA a = ...; printf("Hello " FORMAT " there", a); printf(FORMAT , a); ```
I'd like to be able to stream video from a camera attached to my computer directly to an FPGA I have attached to my computer via PCIE. I don't mind using a high level language like javascript or C# to do this (as those are the langauges I know have video streaming abilities), but I recognize that in order to get to t...
I may be wrong, but it sounds to me you'll need to write a kernel driver for your hardware. This means you'll need to learn kernel development. For Windows, you need the WDK, Windows Driver Kit. I'm not familar with Linux kernel development.
This question already has answers here:How can I get the size of a memory block allocated using malloc()? [duplicate](9 answers)Closed4 years ago. I have a buffer and want to do a test to see if the buffer has sufficient capacity I.e. find number of elements I can add to the buffer. ``` char *buffer = (char *)malloc...
For GNU glibc: ``` SYNOPSIS #include <malloc.h> size_t malloc_usable_size (void *ptr); ``` DESCRIPTION The malloc_usable_size() function returns the number of usable bytes in the block pointed to by ptr, a pointer to a block of memory allocated by malloc(3) or a related function.
Is it possible to resize the console in a windows console application to fullscreen size? It is possible to do that in the preferences of the windows, after the console was opened, but I cannot figure out how to do it programmatically.
You can get a handle to the console window usingGetConsoleWindow. Once you have that, you should be able to resize it usingSetWindowPos You may also need to resize the buffer for the console usingSetConsoleScreenBufferSizeprior to resizing the window. ETA: Others have mentioned using SetConsoleDisplayMode to displ...
I know thatreadis system call. But when I readman 2 and man 3of read it shows me different explanation. So , I am suspecting thatreadhas library function and system call. In such case if I usereadin my c program, whether compiler will consider read aslibraryfunction orsystem callPlease explain me on this confusion.
It doesn't. System calls are present in libc (the C standard library) just like library functions are. The implementations of system calls in libc are just "stubs" which invoke system-specific methods of calling into the kernel.