question
stringlengths
25
894
answer
stringlengths
4
863
My process is accessing a shared memory that is already created. The pointer attached to the shared memory is a structure containing a pointer and 2 or 3 variables. eg: ``` typedef struct _info_t{ int id; char c; }info_t; typedef struct _details_t{ int buff_id; info_t* info; }details_t; details_t* ...
If a memory segment is shared between more than one process, there's no guarantee it will be mapped at the same address, so you cannot store pointers in shared memory segment. Try to avoid using pointers, use offsets or arrays (if possible).
I installed a Python package (such as SQLAlchemy), and it compiled C into binaries on a Windows 7 machine. Can I expect to be able to reuse the compiled binaries on Windows Server 2008-R2? Edit:Both are AMD64 Python 2.7.3 and Windows 64 bit.
Yes, but there are other issues you need to watch-out for. Are both systems either 32-bit or 64-bit? Not just the hardware, but the Python version as well. Are both systems running the same version of Python? That's tied to both major and minor version numbers (seesys.version_info). Edit: Your edit has answered ...
Why does this code not work? ``` char *x=malloc(100); x++; x=realloc(x, 200); ``` I mean x is a valid string pointer, just incremented by one?
See C Standard (C99, 7.20.3.4p3) onreallocand my emphasis: void *realloc(void *ptr, size_t size);If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. Otherwise,if ptr does not match a pointer earlier returned by the calloc, malloc, or realloc function,or if the s...
I need to understand what the commented line does? ``` #include <stdio.h> void fun(char**); int main() { char *argv[] = {"ab", "cd", "ef", "gh"}; fun(argv); return 0; } void fun(char **p) { char *t; t = (p+= sizeof(int))[-1]; //what this line does? //[-1] does what? printf("%s\n", t); } ```
Assuming thatintis 4 bytes in your machine, then replacesizeof(int)with 4: ``` t = (p+= 4))[-1]; ``` is just to move forward the pointerp4 elements, and move backward 1 element, then get the element. In this example, the array has 4 elements, so move forward to one past the end, and move backward to the last elemen...
I am reading a book about network progamming in C. It is from 2004. In the example code, author is usingselectC function to accept multiple connections from the client. Is that function deprecated today? I see that there are different ways to accept multiplexed I/O likepollandepoll. What are the advantages?
It's not deprecated, and lots of programs rely on it. It's just not the best tool as it has some limitations: The number of file descriptors is limited (OS specific, usually possible to increase it with kernel recompiling).Doesn't scale well (with lots of fds): the whole FD set must be maintained, and re-initialized...
Why doesn't the following loop run infinite times? I expect that upon reaching 65535,ishould overflow back to zero. ``` #include<stdio.h> int main() { short int i = 0; //(assume short int is 2 bytes) for(i<=5 && i>=-1; ++i; i>0) printf("%u\n", i); return 0; } ``` EDIT What about this ``` #incl...
You are relying on signed overflow here, which invokesundefined behvaiour. The compiler would be well within its rights to optimize this to an infinite loop, or not, or to do something completely different.
Does the C99/C++11 standard guarantee thatsizeof(size_t) == sizeof(void*)is always true? ``` size_t f(void* p) { return (size_t)(p); // Is it safe? } void* f(size_t n) { return (void*)(n); // Is it safe? } ```
No, that is not guaranteed. Useintptr_toruintptr_tto safely store a pointer in an integer. There are/were architectures where it makes sense for that to be false, such as the segmented DOS memory model. There the memory was structured in 64k segments - an object could never be larger than a segment, so 16-bitsize_two...
When I do something like ``` typedef long a; extern a int c; ``` It gives me error :two or more data types in declaration specifiers.Why? EDIT ``` typedef long a; extern a c; ``` works fine.So why not above?
It's a typedef, not a macro. The compiler doesn't seeextern long int c, it seesextern a int c, which contains two different types (aandint).
Please consider the following code ``` #include<stdio.h> int fun(); /* function prototype */ int main() { int (*p)() = fun; (*p)(); return 0; } int fun() { printf("IndiaBix.com\n"); return 0; } ``` What isint(*p)()here?Is it a function,variable or what?
Flowspiral rule: ``` +------+ | | | +-+ | | ^ | | int ( *p ) () ^ | | | | +----+ | +--------+ Identifier p is a pointer to.. is a pointer...
Is there special hardware or software to program an FPGA? Can it be done in higher level languages? Does running an application on an FPGA "lock it in" to that execution path?
Is there special hardware or software to program an FPGA?Yes. For hardware, usually we program FPGA using a USB-JTAG programming cable. For software, If you chooseXilinx's FPGA, youmustuse Xilinx ISE. If you chooseAltera's FPGA, youmustuse Quartus II. Can it be done in higher level languages?Two popular hardware desc...
I'm wondering why such code generates following error while compiling: 1.c:11: error: expected expression before 'else' code: ``` #include <stdio.h> #define xprintk(...) while(0); int main (void) { if (1) xprintk("aaa\n"); else xprintk("bbb\n"); return 0; } ```
``` #define xprintk(...) while(0) ^^ Remove semi-colon ``` See what happens after pre-processing gcc -E test.c ``` int main (void) { if (1) while(0);; //<- Two semi-colon (i.e. Two statements) else while(0);; //<- Two semi-colon return 0; } ```
My program is accepting user input and then taking the first word inputted and comparing it to an array of accepted commands. What would be the best way to compare the first word inputted (after it has been tokenized) to an array of strings? Example: comparing the string"pwd"to an array containging{"wait", "pwd", "c...
I would do something like the following: ``` int string_in(const char* string, const char** strings, size_t strings_num) { for (size_t i = 0; i < strings_num; i++) { if (!strcmp(string, strings[i])) { return i; } } return -1; } ``` Check each string in the array, if it's the s...
I'm working on a programming project and one of things I need to do is write a function that returns a mask that marks the value of the least significant 1 bit. Any ideas on how I can determine the value using bitwise operators? ``` ex: 0000 0000 0000 0000 0000 0000 0110 0000 = 96 What can I do with the # 96 to tur...
``` x &= -x; /* clears all but the lowest bit of x */ ```
What is the difference between these two declarations, if someone could explain in detail: ``` typedef struct atom { int element; struct atom *next; }; ``` and ``` typedef struct { int element; struct atom *next; } atom; ```
This is Normalstructure declaration ``` struct atom { int element; struct atom *next; }; //just declaration ``` creation ofobject ``` struct atom object; ``` ``` struct atom { int element; struct atom *next; }object; //creation of object along with structure declaration ``` ...
A Small C question for you, appreciate your help: A file's first line is:"add A"It has more lines beneath. I'm reading the first line from the file using fgets: ``` char str [500]; fgets(str,sizeof(str),filePointer); ``` Since fgets stops at the newline char, I replace the unwanted newline char with '\0': ``` cha...
Your file likely uses\r\nline-endings (aka. Windows line-endings) and you therefore left a trailing\rin. Kill the\ras well and you should be done.
Whilst looking at the Intel Intrinsics pdf (to try and work out which headers need to be included) I can see that there is<ia64intrin.h>header. However, I only seem to have<ia32intrin.h>available. What do I need to do to setup the ability to useallIntel intrinsics features? I have the Intel C/C++ compiler....
Do try to focus on the intrinsics that are supported by the specific processor you want to target. That is pretty unlikely to be an Itanium these days. So unusual that it isn't included anymore, the Itanium compiler is a separate download.
I am trying to write MPI code with scanf which will take input for all process individually, but only one process taking the input from user and others assign garbage value to that variable. The program is as below ``` #include <stdlib.h> #include <stdio.h> #include "mpi.h" #include<string.h> int main(int argc, char...
stdin is only forwarded to rank 0. In any case, reading from stdin is a bad idea with a capital VERY, and is not supported by the standard.
I'm using Code Composer Studio which is based on eclipse Indigo. My Programm is written in C. I want to rename some macros via context-menu-->refactor-->rename. It is possible to get into "refactor mode" but eclipse refuses to do the refactoring after I press return (the macro name is changed to the old value). Is the...
Open therename dialogby typingAlt+Shift+Rtwice. See whether it works.UseSourceInsightsmart rename function.As Basile mentioned, use text editor like Emacas and Vi.
I am working on this code: ``` struct box { char word[200][200]; char meaning[200][200]; int count; }; struct root { box *alphabets[26]; }; root *stem; box *access; void init(){ //cout<<"start"; for(int i = 0 ; i<= 25; i++){ struct box *temp =(struct box*)( malloc(sizeof(struct box)*...
Makestemastruct, not a pointer: ``` root stem; // No asterisk ``` Otherwise, there's no memory allocated to it, so dereferencing it is undefined behavior. Of course you need to replacestem->alphabets[i]withstem.alphabets[i].
I have a methodWriteValuethat writes aDWORDvalue to the registry: ``` const char *WriteValue(char* searchHandleId) { //... DWORD value = atoi(searchHandleId); // wrong!!! LONG result_write = RegSetValueEx( hkey, "hwnd_to_track", ...
``` DWORD value = strtoul(searchHandleId, NULL, 16); ```
Is there any way to delete the first character in a text file once you read it? I want the program to read the character in from the text file and once it is used it should delete that current character that was read from the text file.
You cannot insert at the beginning, remove at the beginning, insert in the middle, remove in the middle of a file without rewriting it. Appending at the end is possible. Sometimes it's possible to delete at the end (depending on the platform).
In my project i have a Header file common.h which include many headers in it.Some of the files include Common.h and some other header which are already present in Common .h So In the Pre-Processing stage many functions get prototyped twice(Once from the Included header and other from Gui.h).I was wondering is this wou...
Headers should haveinclude guardsso that they are only processed once: ``` #ifndef SOME_UNIQUE_STRING #define SOME_UNIQUE_STRING // Everything else here #endif ``` By "Everything" I mean "everything", starting with your#includes if any. SOME_UNIQUE_STRING could be the name of the module as long as it is unlikely ...
Is there any inbuilt function available two get string between two delimiter string in C/C++? My input look like ``` _STARTDELIMITER_0_192.168.1.18_STOPDELIMITER_ ``` And my output should be ``` _0_192.168.1.18_ ``` Thanks in advance...
You can do as: ``` string str = "STARTDELIMITER_0_192.168.1.18_STOPDELIMITER"; unsigned first = str.find(STARTDELIMITER); unsigned last = str.find(STOPDELIMITER); string strNew = str.substr (first,last-first); ``` Considering yourSTOPDELIMITERdelimiter will occur only once at the end. EDIT: As delimiter can occur ...
I'm slinging some C code and I need to bitshift a 32 bit int left 32 bits. When I run this code with the parameter n = 0, the shifting doesn't happen. ``` int x = 0xFFFFFFFF; int y = x << (32 - n); ``` Why doesn't this work?
Shift at your own peril. Per the standard, what you want to do isundefined behavior. C99 §6.5.73- The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the pro...
This question already has answers here:Why is a string's byte size longer than the length? [closed](2 answers)Closed9 years ago. if you have ``` char test1[] = { 'a', 'b', 'c' }; char test2[] = "abc"; ``` I understandsizeof(test1)is 3 since char is only 1 byte hence 1x3 = 3 BUT why isnt thesizeof(test2)3? y is i...
test2 is actually a terminated string so one more char for this '\0' so the size is 4. ``` test2[] = { 'a', 'b', 'c', '\0' }; ```
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ...
lockblocks and only returns when it has the lock,trylockreturns immediately and can either succeed or fail to obtain the lock. Amanualcan usually answer such questions.
I'm trying to model a struct found in a library I'm wrapping, where the struct has a pointer-to-a-pointer like this: ``` typedef struct item_t { char* name; } typedef struct container_t { item_t **items; } ``` How, when modeling with Python'sctypesmodule'sStructureclass, would I represent an array of pointers w...
You can usePOINTERand convertitem_t **toPOINTER(POINTER(item_t)): ``` from ctypes import * class item_t(Structure): _fields_ = [ ('name', c_char_p), ] class container_t(Structure): _fields_ = [ ('items', POINTER(POINTER(item_t))), ] ```
I need to be able to get theCPU timefor the current process from inside some C code. On Linux, I can useclock_gettimewithCLOCK_PROCESS_CPUTIME_ID. On BSD I can useclock_gettimewithCLOCK_VIRTUAL. On Windows,GetProcessTimes. What is the OS X alternative?
You have a couple of options: clock()(standard C)getrusage()(POSIX) There's also a Mach API task_info() but it doesn't seem to offer any obvious benefit over the portable alternatives for querying CPU time.
I am trying to write MPI code with scanf which will take input for all process individually, but only one process taking the input from user and others assign garbage value to that variable. The program is as below ``` #include <stdlib.h> #include <stdio.h> #include "mpi.h" #include<string.h> int main(int argc, char...
stdin is only forwarded to rank 0. In any case, reading from stdin is a bad idea with a capital VERY, and is not supported by the standard.
I'm using Code Composer Studio which is based on eclipse Indigo. My Programm is written in C. I want to rename some macros via context-menu-->refactor-->rename. It is possible to get into "refactor mode" but eclipse refuses to do the refactoring after I press return (the macro name is changed to the old value). Is the...
Open therename dialogby typingAlt+Shift+Rtwice. See whether it works.UseSourceInsightsmart rename function.As Basile mentioned, use text editor like Emacas and Vi.
I am working on this code: ``` struct box { char word[200][200]; char meaning[200][200]; int count; }; struct root { box *alphabets[26]; }; root *stem; box *access; void init(){ //cout<<"start"; for(int i = 0 ; i<= 25; i++){ struct box *temp =(struct box*)( malloc(sizeof(struct box)*...
Makestemastruct, not a pointer: ``` root stem; // No asterisk ``` Otherwise, there's no memory allocated to it, so dereferencing it is undefined behavior. Of course you need to replacestem->alphabets[i]withstem.alphabets[i].
I have a methodWriteValuethat writes aDWORDvalue to the registry: ``` const char *WriteValue(char* searchHandleId) { //... DWORD value = atoi(searchHandleId); // wrong!!! LONG result_write = RegSetValueEx( hkey, "hwnd_to_track", ...
``` DWORD value = strtoul(searchHandleId, NULL, 16); ```
Is there any way to delete the first character in a text file once you read it? I want the program to read the character in from the text file and once it is used it should delete that current character that was read from the text file.
You cannot insert at the beginning, remove at the beginning, insert in the middle, remove in the middle of a file without rewriting it. Appending at the end is possible. Sometimes it's possible to delete at the end (depending on the platform).
In my project i have a Header file common.h which include many headers in it.Some of the files include Common.h and some other header which are already present in Common .h So In the Pre-Processing stage many functions get prototyped twice(Once from the Included header and other from Gui.h).I was wondering is this wou...
Headers should haveinclude guardsso that they are only processed once: ``` #ifndef SOME_UNIQUE_STRING #define SOME_UNIQUE_STRING // Everything else here #endif ``` By "Everything" I mean "everything", starting with your#includes if any. SOME_UNIQUE_STRING could be the name of the module as long as it is unlikely ...
Is there any inbuilt function available two get string between two delimiter string in C/C++? My input look like ``` _STARTDELIMITER_0_192.168.1.18_STOPDELIMITER_ ``` And my output should be ``` _0_192.168.1.18_ ``` Thanks in advance...
You can do as: ``` string str = "STARTDELIMITER_0_192.168.1.18_STOPDELIMITER"; unsigned first = str.find(STARTDELIMITER); unsigned last = str.find(STOPDELIMITER); string strNew = str.substr (first,last-first); ``` Considering yourSTOPDELIMITERdelimiter will occur only once at the end. EDIT: As delimiter can occur ...
I'm slinging some C code and I need to bitshift a 32 bit int left 32 bits. When I run this code with the parameter n = 0, the shifting doesn't happen. ``` int x = 0xFFFFFFFF; int y = x << (32 - n); ``` Why doesn't this work?
Shift at your own peril. Per the standard, what you want to do isundefined behavior. C99 §6.5.73- The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the pro...
This question already has answers here:Why is a string's byte size longer than the length? [closed](2 answers)Closed9 years ago. if you have ``` char test1[] = { 'a', 'b', 'c' }; char test2[] = "abc"; ``` I understandsizeof(test1)is 3 since char is only 1 byte hence 1x3 = 3 BUT why isnt thesizeof(test2)3? y is i...
test2 is actually a terminated string so one more char for this '\0' so the size is 4. ``` test2[] = { 'a', 'b', 'c', '\0' }; ```
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ...
lockblocks and only returns when it has the lock,trylockreturns immediately and can either succeed or fail to obtain the lock. Amanualcan usually answer such questions.
I'm trying to model a struct found in a library I'm wrapping, where the struct has a pointer-to-a-pointer like this: ``` typedef struct item_t { char* name; } typedef struct container_t { item_t **items; } ``` How, when modeling with Python'sctypesmodule'sStructureclass, would I represent an array of pointers w...
You can usePOINTERand convertitem_t **toPOINTER(POINTER(item_t)): ``` from ctypes import * class item_t(Structure): _fields_ = [ ('name', c_char_p), ] class container_t(Structure): _fields_ = [ ('items', POINTER(POINTER(item_t))), ] ```
I need to be able to get theCPU timefor the current process from inside some C code. On Linux, I can useclock_gettimewithCLOCK_PROCESS_CPUTIME_ID. On BSD I can useclock_gettimewithCLOCK_VIRTUAL. On Windows,GetProcessTimes. What is the OS X alternative?
You have a couple of options: clock()(standard C)getrusage()(POSIX) There's also a Mach API task_info() but it doesn't seem to offer any obvious benefit over the portable alternatives for querying CPU time.
In Xcode, whenever I want to use a file (in C or C++ specifically), I have to specify the full path to the file, whereas with gcc or g++, I do not have to if it is in the same directory as the code referencing it. Is there a reason to why this is? And if so, is there a way to fix it?
The problem isn't that "XCode" doesn't accept a relative path. The problem is that your code has a different current working directory than you think. You can, as the comment says, usechdirto get to a place where your file is, or use a relative path that takes into account the currend working directory (you can useget...
I'd like to create a function that returns the percentage of a number as an int (in this case 10%, so it would return 10% of the int passed in), for example if you passed 76, it would return 8. Essentially it is like the function below, but I'm thinking that there must be a better way to do it. ``` int percent(int y)...
``` int percent(int y){ return (y + 5) / 10; } ``` You have integer division there, so it would work for rounding!
I am writing C code for 'password prompt' . I need to display * for every character the user enters . But I am not supported withgetch(). So , I tried system calls .Example , ``` for(i=0;i<5;i++) { system("stty -echo"); scanf("%c", &a[i]); system("stty echo"); printf("*"); } ``` But it does not prin...
You can use non-canonical mode without echo. See an example here In this example, I modified the following lines ``` else putchar (c); ``` with ``` else { putchar (c+1); fflush(stdout); } ```
e.g. ``` union { int n; void *p; } u; ``` Is the initial value of u.n or that of u.p equal to 0? It should be noted that a NULL pointer is not necessarily stored in all-zero bits. Therefore, even if u.n and u.p have the same size, ``` u.n == 0 ``` doesn't guarantee ``` u.p == 0 ``` and vice versa. (Sor...
if Object with Static storage duration is not initialized explicitly, then: — if it has pointer type, it is initialized to a null pointer; — if it has arithmetic type, it is initialized to (positive or unsigned) zero; — if it is an aggregate, every member is initialized (recursively) according to these rules; — if...
Im new to gtk+ 3 and I want to create for my app, Preferences dialog. Don't use glade only C. My questions is how create space between green line and red line using gtk_grid. Tanks for any help Align "Start playing files..." check box at 20 relative to "Playback" label.
As the GtkGrid documentation says: GtkGrid is a container which arranges its child widgets in rows and columns. It is a very similar to GtkTable and GtkBox, but it consistently uses GtkWidget's "margin" and "expand" properties instead of custom child properties, and it fully supports height-for-width geometry...
K&R says compilers are free to ignore the advice (register declaration). In what cases, gcc would ignore if I defineregister int x = 4;?
This is totally implementation-dependent. In general, you should trust the compiler to put variables to register and not define them yourself. C99 6.7.1 Storage-class specifiersA declaration of an identifier for an object with storage-class specifierregistersuggests that access to the object be as fast as possible. ...
What is the meaning of the following macro definition? ``` #define REG(x) (*((volatile unsigned int *)(x))) ```
It castsxas avolatile unsigned intpointer, and then dereferences that pointer to get the value of whatx"points" to. Note thatxdoesn't actually need to be declared as a pointer, it could as well be a literal integer that is then treated as an address to somewhere in memory. Useful on embedded systems or in kernel boot...
In the below code if I read image usingimreadthe image is displaying differently and if the source is camera it is showing normal colored image. And below is the code. Can some one explain bit in detail with some good link if possible? ``` int main () { cv :: Mat_<unsigned char> src; cv :: VideoCapture cap(...
BothVideoCaptureandimreadwithout additional parameter returns 3-channels BGR frames. Usecv::Mat_<cv::Vec3b>type.
As far as I know,CdefinesNULLlike this: ``` #define NULL ( (void *) 0) ``` Then, how should we defineNULL_POINTER? I defined it the same in my program and it worked, but I suppose that is just a coincidence: ``` #define NULL_POINTER ( (void *) 0) ``` What would be the logical definition, if any ?
``` #define NULL ( (void *) 0) ``` and ``` #define NULL 0 ``` are both valid. If you need to implement your own macro for null pointer, the same rule applies. C11(ISO/IEC 9899:201x) §6.3.2.3PointersSection 3An integer constant expression with the value0, or such an expression cast to typevoid *, is called a null p...
I have a quirky problem where if I input say 720.60 into ``` sscanf("%f", &amount); ``` where amount is of type float, the value in the variable changes to 720.59967. How can I bypass this and prevent it from changing my value?
You can print fewer digits, or usedouble. Asingle precision IEEE-754floatvalue has a 23 bit mantissa, which means it has about 7 decimal digits of precision. The value you see is as close as it can get: there is nofloatvalue closer to 720.60 than 720.59967. In fact, the exact values of the twofloatvalue closest to 72...
``` while ((client = accept(sock, (struct sockaddr *) &c, (socklen_t *) &clientlength)) > 0) { int h = 0; int i = 0; char el[4] = "\r\n\r\n"; while (recv(client, r , 1, 0) != 0) { if (h==4) break; if (*r == el[h]) { h++; } *r++; i++; } } ``` This is a server progra...
Move h==4 check down as below ``` if(*r==el[h]){ h++; } r++; i++; if (h==4) break; ```
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed10 years ago.Improve this question I need to convert VB.NET to any of C, C++, or Java. I really don't care how many steps ...
You should take a look at the haxe programming language. I've never used it myself but it would seem that it can be compiled to JavaScript, Flash, NekoVM, PHP, C++, C# and Java (taken fromhttp://haxe.org/). While VB.NET is not in there, C# can be pretty similar.
I have been working on some C code on a windows machine and now I am in the process of transferring it to a Linux computer where I do not have full privileges. In my code I link to several static libraries. Is it correct that these libraries need to be re-made for a Linux computer? The library in question is GSL-1....
Yes, you do need to compile any library again when you switch from Windows to GNU/Linux. As for how to do that, you don't need automake to build GSL. You should read the file INSTALL that comes inside the tarball (the file gsl-1.16.tar.gz) very carefully. In a nutshell, you run the commands ``` $ ./configure $ make ...
I know I can check my OS name with this simple command:lsb_release -ds. But I also know, that its not portable on all platforms where I need it. I triedstruct utsname info;anduname(&info)and it works great but gives me only "base" name - "Linux". Is there any portable (C) way of getting full OS name? Portable between...
Here is the C code that says the name of the OS. You can also edit the code for other various purpose, by using the same logic. ``` #include<stdio.h> int main() { FILE *fp; char buffer[50] = " "; fp = popen("lsb_release -ds", "r"); fgets(buffer, 50, fp); pclose(fp); printf("Name of the OS is ...
I need to write a functionint median(int d[], int size)in C that finds the median of an array. The function needs to call a functionvoid selectsort(int d[], int size)that sorts the array for themedian()function. Only themedian()function is allowed to call theselectsort()function. How can I get the sorted array fromse...
Presumablyselectsortsorts the array in place, destroying the original ordering. Simply passdtomedianafter callingselectsort.
For example, if I want to delete 10 bytes in the middle of file or add 10 bytes to the middle, are there anyway to do it without total file rewrite? I'd like a solution that does this task the fastest. I use C#, but the solution maybe be also in C or C++.
You have to copy the entire file, omitting or inserting the relevant bytes. This is an OS constraint; because of the way files are laid out on disk, it simply isn't possible to support this type of operation (at least with simple file systems like those used by Unix or Windows).
I am trying to figure out the total number of user processes that Minix 2.0.4. I wrote a program that will perform forks until the forks fail and forks fails after 14 forks are executed and paused. So I think it would be 16 total user processes including the program executing the code and the shell. Can anyone provide...
If you callforkin a loop, and do not limit the children from forking themselves, each child will callforkas well, and so on until no more processes can be created. The actual number of processes will then be much more than counted in the topmost parent process.
Code: ``` int main() { char *name=NULL; int n; printf("\nenter the string\n"); scanf("%s",name); n=strlen(name); printf("%d",n); return 0; } ``` I am getting segmentation fault. Whats wrong with the code? I have includedstdio.h,stdlib.h,string.h.
You didn't allocate any memory for pointer to charname. Example: ``` char * name = malloc( sizeof( char ) * MAX_STRING_LENGTH ) ; ```
For example, if I want to delete 10 bytes in the middle of file or add 10 bytes to the middle, are there anyway to do it without total file rewrite? I'd like a solution that does this task the fastest. I use C#, but the solution maybe be also in C or C++.
You have to copy the entire file, omitting or inserting the relevant bytes. This is an OS constraint; because of the way files are laid out on disk, it simply isn't possible to support this type of operation (at least with simple file systems like those used by Unix or Windows).
I am trying to figure out the total number of user processes that Minix 2.0.4. I wrote a program that will perform forks until the forks fail and forks fails after 14 forks are executed and paused. So I think it would be 16 total user processes including the program executing the code and the shell. Can anyone provide...
If you callforkin a loop, and do not limit the children from forking themselves, each child will callforkas well, and so on until no more processes can be created. The actual number of processes will then be much more than counted in the topmost parent process.
Code: ``` int main() { char *name=NULL; int n; printf("\nenter the string\n"); scanf("%s",name); n=strlen(name); printf("%d",n); return 0; } ``` I am getting segmentation fault. Whats wrong with the code? I have includedstdio.h,stdlib.h,string.h.
You didn't allocate any memory for pointer to charname. Example: ``` char * name = malloc( sizeof( char ) * MAX_STRING_LENGTH ) ; ```
I am having trouble with C more than I thought I would. The goal of this segment of code is to read input from user and then based on that integer input the line "hello world" that number of times. I tried multiple different ways but every time my code would only execute 1 time.. Any suggestions? ``` #include <stdio....
First, you don't have to usedouble, which is a floating-point type. An integer is sufficient. ``` scanf("%d", &x); ``` Decrementingxinforloop is useless:Hello worldwill be printed from(x - 1) - 0 + 1 = xtimes without this instruction. ``` for (int i = 0; i < x; i++) { printf("Hello world.\n"); } ```
Sorry I am new to C. But what am I doing wrong? Tried almost everything, but still can not calculate seconds passed to execute the code between t1 and t2, always returns me Finished in 0.00 seconds. Thanks for your patience :) ``` #include <time.h> clock_t t1, t2; t1 = clock(); sleep(5); t2 = clock(); printf("\nFi...
If coarse granularity (whole second) is ok, perhapstime(2)andtime_tare good enough. Example: ``` #include <stdio.h> #include <time.h> #include <unistd.h> static time_t t1, t2; int main(void) { t1 = time(0); (void) sleep(5); t2 = time(0); (void) printf("\nFinished in %d seconds.\n\n", (int) (t2-t1)); re...
If we want to integrate C/C++ into python using internal Python API. Then signature of functions are in the following forms ``` static PyObject *MyFunction( PyObject *self, PyObject *args ); static PyObject *MyFunctionWithKeywords(PyObject *self, PyObject *args, ...
From thedocs: Portability therefore requires not to make any assumptions about symbol visibility. This means that all symbols in extension modules should be declaredstatic, except for the module’s initialization function, in order to avoid name clashes with other extension modules (as discussed in section The...
I am developing application using OpenSSL API. As it known, OpenSSL uses miriades of global variables which are taken by Valgrind as errors ("conditional jump or move..." etc). Thus the Valgrind's output gets clogged with errors from shared libraries. This is very inconvenient for debug purposes, because every time I ...
Adding the option ``` --undef-value-errors=no ``` works for me (hide all "Conditional jump or move depends on uninitialised value(s)"). For more information see Valgrind'sman page.
I wanted to read a value which is stored at an address whose absolute value is known. I am wondering how could I achieve this. For example. If a value is stored at 0xff73000. Then is it possible to fetch the value stored here through the C code. Thanks in advance
Two ways: 1. Cast the address literal as a pointer: ``` char value = *(char*)0xff73000; ``` Cast the literal as a pointer to the type. and De-reference using the prefix*. Same technique applies also to other types. 2. Assign the address to a pointer: ``` char* pointer = (char*)0xff73000; ``` Then access the v...
This question already has answers here:Determine size of dynamically allocated memory in C(15 answers)Closed10 years ago. ======================================================================================= HI If we given a dynamically allocated pointer, how can we determine the size of allocated memory? For E...
You can't, at least not without seriously dirty hacks. You should know how much you allocated, and you shouldn't care about the memory you didn't allocate.
I print out msghdr.msg_namelen after recvmmsg() returns but it is not set. However, msg_len is set correctly. I am listening for multicast traffic (i.e. datagram). Is there anything I need to do in order for recvmmsg() to populate msghdr? I have also tried to call recvmsg() instead. msghdr isn't populated either....
In kernel, recvmsg() and recvmmsg() both have the common subcall, which just uses the msg_namelen and msg_name as the input arg. That is to say, you must set those members yourself. You can try to think that way, the msg_name is a pointer to a string area that you supply to kernel before calling the recvmsg(). If you...
Why does the static assert fire in this case? Are these at the same address because of 64 bit address lines and a char is a single byte? ``` #include <type_traits> int main() { char a='a'; char b='b'; static_assert ( &a == &b, " ERROR: Same addr" ) ; } main.cpp: In function ‘int m...
You've got the logic backwards.static_assertis triggered when the condition isfalse, that is, the two object don't have the same address.
I have some rather complex and highly templated code (C++, but this may not be very relevant) of which I'd like to know the number of adds, subs, muls, divs, and sqrts at execution. Is there an automatic way to get this information (the compiler could work it out easily)? I tried to count it myself in the assembler co...
I would suggest to override+,-,*,/operators andsqrtfunction for some float-like type, in which you can count their use. Something like this: ``` struct Double { double val; Double(double v): val(v) {} static unsigned add_count = 0; Double operator+(Double other) { ++add_count; return ...
When I do: ``` FILE * fp = fopen("filename", "r");` ``` How can I know the file pointer fp points to a file or a directory? Because I think both cases the fp won't be null. What can I do? The environment is UNIX.
i've found this near by: ``` #include <stdio.h> #include <errno.h> #include <sys/stat.h> int main (int argc, char *argv[]) { int status; struct stat st_buf; status = stat ("your path", &st_buf); if (status != 0) { printf ("Error, errno = %d\n", errno); return 1; } // Tell us...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed10...
To remove all environment variables in Linux with GNU C Library you can useclearenv(). When this function is not available (it is not in POSIX) you can useenviron = NULLinstead. Do this before callingexecl()or any variant. If you are calling someexec()variant you can set the environment directly with the call (varian...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed10...
Check theerrnoglobal variable right after callingfopen. strerror(errno); to get specific error information as as string.
I have a small problem that I can't seem to fix. Say I have a string, buffer = "1 1 X ./simple E" And I want to extract the 2 ints, 2 chars and the filename, sscanf(buffer, "%d %d %c %s %c, &a, &b, &c, d, &e); printf("%d %d %c %s %c", a, b, c, d, e); I don't get back quite what I expect. I get "11 1 X (null)". An...
You are declaringchar *d, which will fail because it has no valid place to point. Use an array that has enough space will do: ``` #include <stdio.h> #include <string.h> int main() { int a, b; char c, e; char d[20]; char buffer[] = "1 1 X ./simple E"; sscanf(buffer, "%d %d %c %s %c", &a, &b, &c, d...
I have converteduint64_ttounsigned char*using the following: ``` uint64_t in; unsigned char *out; sprintf(out,"%" PRIu64, in); ``` Now I want to do the reverse. Any idea?
The direct analogue to what you're doing withsprintf(3)would be to usesscanf(3): ``` unsigned char *in; uint64_t out; sscanf(in, "%" SCNu64, &out); ``` But probablystrtoull(3)will be easier and better at error handling: ``` out = strtoull(in, NULL, 0); ``` (This answer assumesinreally points to something, analogou...
Division in processor takes much time, so I want to ask how to check in fastest way if number is divisible of some other number, in my case I need to check if number is divisible by 15. Also I've been looking through web and foundfunways to check if number is divisible of some number, but I'm looking for fast option....
Obligatory answer for other learners who might come looking for an answer. if (number % n == 0) Inmostcases, you can always do this, trusting the smart modern compilers. This doesn't mean you get discouraged from learning fun ways though. Check out these links. Fast divisibility tests (by 2,3,4,5,.., 16)? Bit Twi...
I've written a code in c: ``` const char *str[125000]; float k[125000]; long n; char string[20]; int i; scanf("%d",&n); for (i=0;i<n;i++) { scanf("%s%f",&string,&k[i]); p=p/k[i]; str[i]=_strdup(string); } ``` At this point everything's perfect. The array gets filled even if the n=100000; How...
Arrays in C the size of n go from 0 to n - 1. So your loop should be ``` for (i=n-1;i>=0;i--) ``` You get an error because you are trying to access memory out of bounds of that array.
I want to read the whole file content and print it out , but I get a segment fault , I can't find what's wrong with the code ... ``` #include <stdio.h> #include <stdlib.h> int main() { FILE * file; long fsize; file = fopen("./input.txt","r"); if(file != NULL){ //get file size fseek(fi...
The pointer you pass tofgets(file_content) is uninitialized. It should be pointing to a block of memory large enough to contain the specified number (fsize) of bytes. You can usemallocto allocate the memory. ``` char* file_content = (char*)malloc(fsize); ```
``` #include <stdio.h> int main() { printf("Hello\c!\n"); return 0; } ``` Output :Helloc! So , when\[some_undifined_symbol]appeared inprintf's format string, it just ignore the\?
\cis not an escape sequence that is already defined, but it's better to avoid using it because it's reserved: C99 §6.11.4 Character escape sequencesLowercase letters as escape sequences are reserved for future standardization. Other characters may be used in extensions.
Can anybody explain why the following code gives the following warning and how to remedy it? ``` warning: assignment makes integer from pointer without a cast [enabled by default] ``` Here is the code: ``` int tcp_socket(void) { int s; if ((s = socket(PF_INET, SOCK_STREAM, 0)) == -1) { _logf(LOG_DE...
Correct this: socket = tcp_socket; to socket = tcp_socket(); tcp_socket()is a function call, whiletcp_socketis a pointer to the function location in memory.
I have some dll i'm not able to load using ctypes.open() method. I have no clue why. It has C extern functions, all other dlls from the same path are loaded correctly. In FF 8 the dll is loaded without issues, I'm trying on FF 22 without any success. Appreciate your assistance here. Guy
Since it was working before, my guess isASLR enforcementon Vista and later. IIRC, the wholeLoadLibrary()function is hooked to prevent loading non-ASLR DLLs at runtime. Try to build your DLL with/DYNAMICBASE. If it is not that, than the likely reason is that your DLL cannot be found. Try to use absolute paths and mak...
This question already has answers here:Return type of main function [duplicate](5 answers)Closed10 years ago. In a book (don't remember which one) they used: ``` void main(void) ``` In school I learned: ``` int main(void) ``` Is thereany casewhenvoid main(void)is actually correct? Or at least not explicitly wrong...
Never, ever usevoid main(void). It is not standard. Always use one of ``` int main(void); int main(); int main(int argc, char **argv); int main(int argc, char *argv[]); ``` And the best use of said book is to use it to light your first fire for the winter.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed10 years ago.Improve this question In which section of memory C language variable names are stored? For example Var_Name is variable name. I ...
It's not stored anywhere. Variable names are just labels for the compiler that have no meaning in the binary code hence they are omitted and replaced by relevant memory addresses/registers.
When I do: ``` FILE * fp = fopen("filename", "r");` ``` How can I know the file pointer fp points to a file or a directory? Because I think both cases the fp won't be null. What can I do? The environment is UNIX.
i've found this near by: ``` #include <stdio.h> #include <errno.h> #include <sys/stat.h> int main (int argc, char *argv[]) { int status; struct stat st_buf; status = stat ("your path", &st_buf); if (status != 0) { printf ("Error, errno = %d\n", errno); return 1; } // Tell us...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed10...
To remove all environment variables in Linux with GNU C Library you can useclearenv(). When this function is not available (it is not in POSIX) you can useenviron = NULLinstead. Do this before callingexecl()or any variant. If you are calling someexec()variant you can set the environment directly with the call (varian...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed10...
Check theerrnoglobal variable right after callingfopen. strerror(errno); to get specific error information as as string.
I have a small problem that I can't seem to fix. Say I have a string, buffer = "1 1 X ./simple E" And I want to extract the 2 ints, 2 chars and the filename, sscanf(buffer, "%d %d %c %s %c, &a, &b, &c, d, &e); printf("%d %d %c %s %c", a, b, c, d, e); I don't get back quite what I expect. I get "11 1 X (null)". An...
You are declaringchar *d, which will fail because it has no valid place to point. Use an array that has enough space will do: ``` #include <stdio.h> #include <string.h> int main() { int a, b; char c, e; char d[20]; char buffer[] = "1 1 X ./simple E"; sscanf(buffer, "%d %d %c %s %c", &a, &b, &c, d...
I have converteduint64_ttounsigned char*using the following: ``` uint64_t in; unsigned char *out; sprintf(out,"%" PRIu64, in); ``` Now I want to do the reverse. Any idea?
The direct analogue to what you're doing withsprintf(3)would be to usesscanf(3): ``` unsigned char *in; uint64_t out; sscanf(in, "%" SCNu64, &out); ``` But probablystrtoull(3)will be easier and better at error handling: ``` out = strtoull(in, NULL, 0); ``` (This answer assumesinreally points to something, analogou...
Division in processor takes much time, so I want to ask how to check in fastest way if number is divisible of some other number, in my case I need to check if number is divisible by 15. Also I've been looking through web and foundfunways to check if number is divisible of some number, but I'm looking for fast option....
Obligatory answer for other learners who might come looking for an answer. if (number % n == 0) Inmostcases, you can always do this, trusting the smart modern compilers. This doesn't mean you get discouraged from learning fun ways though. Check out these links. Fast divisibility tests (by 2,3,4,5,.., 16)? Bit Twi...
I've written a code in c: ``` const char *str[125000]; float k[125000]; long n; char string[20]; int i; scanf("%d",&n); for (i=0;i<n;i++) { scanf("%s%f",&string,&k[i]); p=p/k[i]; str[i]=_strdup(string); } ``` At this point everything's perfect. The array gets filled even if the n=100000; How...
Arrays in C the size of n go from 0 to n - 1. So your loop should be ``` for (i=n-1;i>=0;i--) ``` You get an error because you are trying to access memory out of bounds of that array.
I want to read the whole file content and print it out , but I get a segment fault , I can't find what's wrong with the code ... ``` #include <stdio.h> #include <stdlib.h> int main() { FILE * file; long fsize; file = fopen("./input.txt","r"); if(file != NULL){ //get file size fseek(fi...
The pointer you pass tofgets(file_content) is uninitialized. It should be pointing to a block of memory large enough to contain the specified number (fsize) of bytes. You can usemallocto allocate the memory. ``` char* file_content = (char*)malloc(fsize); ```
When I try to separete token this "(555) 333-444", below code is not giving the desired output. I need function to separate all these 555, 333, 444 separately. What can be my mistake? Output: 555 333-444 ``` #include <stdio.h> #include <string.h> int main(void){ char *ptr; char tel[]="(555) 333-444"; ptr=strto...
This: ``` ptr=strtok(NULL," "); ``` Should actually be: ``` ptr=strtok(NULL,"-() "); ``` You need to always indicate the delimiters you're going to use in the loop.strtokwon't "remember" them. Or you could have something likeconst char* delimiters = "-() ";and just use that every time you usestrtokwith that set o...
I am trying to decode string into its contents but the programs output is not as intended. Output is: -858993623 444 333 What is -858993623? ``` #include <stdio.h> int main(void){ int areaCode; long phoneNumber1; long phoneNumber2; char bracket1, bracket2, chard; char tel[]="(555) 444-333"; sscanf(tel, "%c%d...
You're in UB land at the moment: Try&bracket1, &areaCode, &bracket2rather than&bracket1, &bracket2, &areaCode. Everything else looks fine.
I am having a code, which contains ``` bool fn() { ... //all the following are boolean functions. return isTrue() &&isMsgReceived() &&isMsgSent(); } ``` The problem is that each of the return boolean functions are themselves quite lengthy and takes much computation. Actually, there is no point in check...
&&already does that for you. IfisTrue()returnsfalse, the next two functions are not even evaluated. It therefore makes sense to put the least expensive function first in a chain of&&s.
I have this piece of code here ``` #include<stdio.h> #define LEN 10 char buf[] = {0xff,0xaa,0xfc,0xe8,0x89,0x00,0x00,0x00,0x60,0x89}; char key[] = "SAMPLE KEY"; int main() { int i; char enc[LEN]; for(i=0;i<LEN;i++) { enc[i] = (key[i % LEN] ^ buf[i]); ...
Changebufandenctype at declaration fromchartounsigned char. It is implementation-defined whethercharis asignedorunsignedtype and in your implementation it is apparently asignedtype.
I try to compile an old program which has these lines in the configure file: ``` 4143 if ac_fn_c_try_compile "$LINENO"; then : 4144 ac_cv_prog_hostcc_works=1 { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 4145 $as_echo "yes" >&6; } else as_fn_error $? "installation or configuration problem: ho...
I found there was a semicolon missing: ``` 4144 ac_cv_prog_hostcc_works=1; { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 ```
I have written a very simple kernel that loads inside QEMU with the help of GRUB. I probably have a problem in pointer calculation, but cannot really figure out what is wrong. The following code works as expected, it prints the given character. ``` char* video = 0xb8000 + 0; char* color = 'A'; *video++ = c; *video+...
Perhaps try prefixing it like this: (char*)0xB8000 ``` char* video = (char*)0xB8000; int pos = 0; video[pos++] = 'A'; video[pos++] = 0x7; ```
This question already has an answer here:empty consolewindow when executing c-programs using scanf-function(1 answer)Closed10 years ago. I wanted to print every time the loop runs to print a text, but my program only print's it when the loop runs the last time. My Code: ``` while (shots>i){ printf ("%s", message);...
Addfflush(stdout);afterprintfto flush your output from buffer tostdout. The output would not go tostdoutbefore buffer being full or special character like '\n' comes, you need to do it manually(by callfflush).
This function works to append text to the end of the window, but I'd like it to append it with a newline/break, appending \n doesn't seem to work. if the current text in the text box is "cat" and i append "dog" the result will be "catdog" but i want it to be: "catdog" ``` void appendmessage(LPCTSTR newText, HWND hw...
You need to append\r\n, not just\n(since this is Windows, not *nix).
I have read that storing a string in a character array(with null termination) allows the string to be manipulated later on (unlike having a pointer to string literal). ``` #include <stdio.h> int main() { char s[10]="Stack"; s[9]='a'; // a gets stored in array and if index is less than 6 string gets changed p...
printfwill only print the characters of a string before theNUL-terminator.When you sets[9]='a';, the contents ofsbecome: ``` {'S', 't', 'a', 'c', 'k', '\0', '\0', '\0', '\0', 'a'} ``` if you prints[9], it's there: ``` printf("%c", s[9]); ``` Have a look atstd::string.