question
stringlengths
25
894
answer
stringlengths
4
863
Please let me know how to round a decimal number like 0.53124 to a nearest multiple of 1/16 which is 0.5. And similarly, when you round 0.46875 we must get 0.5. Thanks
``` floor(0.53124 * 16 + 0.5) / 16 floor(0.46875 * 16 + 0.5) / 16 floor(x * 16 + 0.5) / 16 ```
So far I've got as far as: ``` #define ADEFINE "23" #pragma message ("ADEFINE" ADEFINE) ``` Which works, but what if ADEFINE isn't a string? ``` #define ADEFINE 23 #pragma message ("ADEFINE" ADEFINE) ``` causes: warning: malformed ‘#pragma message’, ignored Ideally I'd like to be able to deal with any value, inc...
To display macros which aren't strings,stringify the macro: ``` #define STRINGIFY(s) XSTRINGIFY(s) #define XSTRINGIFY(s) #s #define ADEFINE 23 #pragma message ("ADEFINE=" STRINGIFY(ADEFINE)) ``` If you have/wantboost, you can useboost stringizeto do it for you: ``` #include <boost/preprocessor/stringize.hpp> #defi...
This question already has answers here:How to find the size of an array (from a pointer pointing to the first element array)?(17 answers)Closed9 years ago. ``` char* username ``` is a pointer to the beginning of a character array (in c). How do I calculate the size of the array, is there is function that can do it?...
use strlen(username). But the array has to terminated by '\0'. Otherwise you cannot do that.
I made this program to print up time in hours,minutes and seconds ``` #include<stdio.h> int main() { float a, b,x,mina,minb,hrsa,hrsb; float seca,secb; FILE *fp = fopen("/proc/uptime", "r"); fscanf(fp, "%f %f", &a, &b); seca=(a)%60; mina=seca/60; hrsa=mina/60; secb=(b)%60; minb=secb/60; hrsb=minb/60; printf("Up...
You can't do mod (%) on floats. Try((long)a)%60;Or even(long long), but the 68 years that 1<<31 seconds provides should be sufficient.... Also, you need another mod operation on minutes, or else 3601 seconds becomes "1 hour 60 minutes, 1 second", instead of "1 hour 0 minutes, 1 second".
I'm attempting to learn C and already I've run into an issue. I assume its trivial but I need to know it. I have written: ``` #include <stdio.h> #include <string.h> int main() { char str_a[20]; strcpy(str_a, "Hello, world!\n"); printf(str_a); } ``` Once I attempt to compile it with: gcc -g -o char_arr...
When usingprintf, the format string is better as a string literal than a variable: ``` printf("%s", str_a); ```
I am writing a Opencv C code in eclipse -Ubuntu. I created an executable in eclipse and I am trying to run it on another ubuntu machine (Both machines have 10.10 Maverick Meerkat).But it does not work. The code is built using openCV libraries which are not available on the other machine.Is there any way to create a st...
You'll need to compile OpenCV as a static library, and then link to it (and any other dependencies) statically with your program. You binary's size will be large, but shouldn't need any of the libraries. When you link to OpenCV statically, you'll also need to link to all of OpenCV's dependencies statically as well. I...
I am looking for code source for Sequential Quadratic Programming with C, C++, Python, Matlab. Any reference? Thanks and regards. -- scipy source is in Fortran. any other references? regards.
Python's scipy.optimize module has some good stuff for solving quadratic programming problems. See here for usage information:http://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html See here for source code:http://sourceforge.net/projects/scipy/files/scipy/
I am programming an ARM chip (STM32F2) "bare-metal". Specifically, I would like to read values held in external SRAM. Reading thereference manualI understand that such memory transactions are done through the FSMC (Flexible Static Memory Controller). I understand how to initialise the FSMC for SRAM read/write operati...
As far as I've understood it, you get "memory-mapped" access through the FSMC controller. So all you need to do is decide in what address space to map the SRAM, and then just access it through pointers initialized to point there.
I have two gcc compilers installed on my system, one isgcc 4.1.2(default) and the other isgcc 4.4.4. How can I check the libc version used bygcc 4.4.4, because/lib/libc.so.6shows the glibc used bygcc 4.1.2, since it is the default compiler.
even easier useldd --version This should return the glibc version being used i.e. ``` $ ldd --version ldd (GNU libc) 2.17 Copyright (C) 2012 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO ``` ... which is the same result as running my libc library ``` $...
Can I directly use command-line arguments as parameters for other functions which I call inmain()? Something like: ``` int main(int argc, char* argv[]) { somefunction(argv[2], argv[3]); } ```
The command line arguments are arguments of main. Suppose a function like this: ``` func1(int a, char *s[]) { } ``` Here a and s are arguments to function func1. They behave like local variables in the function. Now you can pass these variables to another function. (like this: ) ``` func1(int a, char *s[]) { ...
Using GDB on the command line, I sometimes break at a certain line of code. At that breakpoint, I can then call functionsas ifmy executable contained the call. How can I get GDB to print the list of all the possible functions that are callable at a given breakpoint?
You could typecalland then hit<tab>(until a list displays). This seems to list the functions contained in the binary.
I am in the midst of creating a text user interface app for a school project. I really need help on how to implement a scroll box or list box in NCurses/PDCurses(in C). As far as I researched,scrollokmakes it possible. I have tried it to my project but to no avail. The scroll box is used for showing list of names ve...
scrollokdoesn't magically create a scroll box, it just allows the window to be scrolled up. You do not even needscrollokfor your purpose. Just maintain an indexito the topmost name which is to be displayed (initially 0)printheighthnames from indexito min(i+h-1,imax) to the window, starting at the topmost linewhen use...
I have the followingtypedeffunction prototype: typedef void (*sa_sigaction_t)(int, siginfo_t *, void *); I have no idea how to use it. I understand that(int, siginfo_t *, void*)istypedef-ed intosa_sigaction_t. But how would I use it? These are all return types with no variable names specified. So I assume I want to...
I understand that (int, siginfo_t, void) is typedef-ed into sa_sigaction_t. Actually no.sa_sigaction_tis a pointer to a function that returnsvoidand takes(int, siginfo_t *, void *)as parameters. So if you have: ``` void foo(int, siginfo_t*, void*) { } ``` you can do: ``` sa_sigaction_t fooPtr = &foo; ``` and the...
I am a little new to C programming. I was writing a C program which has 3 integers to handle. I had all of them inside an array and suddenly I had a thought of why should I not use a structure. My question here is when is the best time to use a structure and when to use an array. And is there any memory usage differe...
An array is best when you want to loop through the values (which, essentially, means they're strongly related). Otherwise a structure allows you to give them meaningful names and avoids the need to document that array, e.g. myVar[1] is the name of the company and myVar[0] is its phone number, etc. as opposed to compan...
Using non-blocking (20 ms cycle) TCP connection in linux, I got a problem: when I close socket from the server side [close(sd) or shutdown(sd,2);close(sd)], the client poll() receives no POLLHUP event.when server is killed from shell, POLLHUP is received. How can I inform client in a cycle or two?
A TCP disconnect is signalled with POLLIN, and a read() will return 0 in the case of a graceful shutdown, or -1 and an appropriate error (errno being anything but EINTR/EWOULDBLOCK). There are platforms where it might be signaled with POLLHUP, so you might want to handle that case too.
I've got problem with this peace of code, it should change lower case letters into upper case, and turn multiple spaces into one space. So what it does wrong, it somehow cuts off the first letter like when i write "abcdefg" it givess me on the output "BCDEFG". ``` main(){ int z=0,b; while ( (b = getchar()...
It seems to generate all the letters for me... have you tried tracing it, to find out what it is doing at each step with the characters you entered?
stdint.hdefines integer types with specified width. When should we use those types, for example,uint32_tinstead ofunsigned int? Is it because we can obtain desired types without considering the underlying machine?
When you need to communicate with other systems and you want to be sure of the length of the data. For example: you save your number to disk. How much long is it on disk? With anunsigned intthe response is "it depends on the compiler, the OS...". Withuint32_tit is 32 bits (4 bytes on "standard" architectures).
I am new to Linux. I made this program for printing uptime and ideal time of my Linux machine. But everytime i run this, it shows idealtime = 0. Can i ever get idealtime=0 ? ``` #include<stdio.h> int main() { int a,b; FILE *fp; fp=fopen("/proc/uptime","r"); fscanf(fp,"%d%d",&a,&b); printf("\n\nUptime =%d \nIdea...
It's because the values are not integers. Try this: ``` float a, b; FILE *fp = fopen("/proc/uptime", "r"); fscanf(fp, "%f %f", &a, &b); printf("Uptime = %d\nIdealtime = %d\n", (int) a, (int) b); ```
I want to write a method called print array that has 2 parameters seen below. I want to, most likely using a for loop, iterate through the array of characters and pass each character to the output text file to be printed on that file on the same line. so if the array has a, b, c, d, e, f, g. in the file I want it to ...
Try this: ``` void printArray(char * array, FILE * fout, int MAX_CHAR) { int i; fout = fopen("file.txt","a+"); /* open the file in append mode */ for (i=0; i<MAX_CHAR; i++) fprintf(file,"%c",*(array+i)); /* write */ fclose(file); /* close the file pointer */ ...
open/read/write are low-level I/O functions, and if speed is of my first concern, how to choose between open/read/write and fopen/fread/fwrite?
The higher level functions provide you with ease of usage also, functions likefopen()provides you with in-built I/O buffering unlikeopen(). The I/O buffering ensuresfopen()is much faster thanopen(). Apart from the above distinction If you have just file descriptor, you should use read, write etc, While If you have aF...
Is there is a more efficient way to remove accents from string without make an big array with the characters to replace? For example: ``` removeaccents("áèfoo") ``` Output: ``` aefoo ``` In the ASCII table there no accents, I have no idea how to do this. Thanks in advance. :)
Sounds like you're looking forunac(). From the man page: unacis a C library that removes accents from characters, regardless of the character set (ISO-8859-15, ISO-CELTIC, KOI8-RU...) as long asiconv(3)is able to convert it into UTF-16 (Unicode). I couldn't find the download page (I think it's meant to b...
I am trying todisplay a compile-time message in GCC, via ``` #pragma message "hello world" ``` But when I compile with-Wallit gives the warning ``` warning: ignoring #pragma message ``` I'm using GCC 4.2.1 on Mac OS X 10.6.8 (Snow Leopard). Why isn't it displaying the message? How can I make it display the messag...
If you read thecorrect documentation, you'll find that#pragma messageisn't supported in GCC 4.2.1.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. What are the differences between pu...
Clean Cis a term coined in Harbison & Steele book (C: A Reference Manual, Prentice Hall). A program is said to be written in Clean C if it can be compiled by a standard C compiler and a standard C++ compiler; and its execution would not produce different observable behavior from the two compilers (the issues of optimi...
I have been using the alarm() system call and an alarm handler in my c program. Recently I decided that I wanted to set the alarm for a time less than a second, so I passed it 0.5, and discovered that the alarm() function accepts an unsigned int. Is it possible to set an alarm for less than a second?
Use theualarm(usecs, interval)method instead.
Please let me know how to round a decimal number like 0.53124 to a nearest multiple of 1/16 which is 0.5. And similarly, when you round 0.46875 we must get 0.5. Thanks
``` floor(0.53124 * 16 + 0.5) / 16 floor(0.46875 * 16 + 0.5) / 16 floor(x * 16 + 0.5) / 16 ```
So far I've got as far as: ``` #define ADEFINE "23" #pragma message ("ADEFINE" ADEFINE) ``` Which works, but what if ADEFINE isn't a string? ``` #define ADEFINE 23 #pragma message ("ADEFINE" ADEFINE) ``` causes: warning: malformed ‘#pragma message’, ignored Ideally I'd like to be able to deal with any value, inc...
To display macros which aren't strings,stringify the macro: ``` #define STRINGIFY(s) XSTRINGIFY(s) #define XSTRINGIFY(s) #s #define ADEFINE 23 #pragma message ("ADEFINE=" STRINGIFY(ADEFINE)) ``` If you have/wantboost, you can useboost stringizeto do it for you: ``` #include <boost/preprocessor/stringize.hpp> #defi...
I declare my struct in a header file like so: ``` typedef struct MyStruct{ int test; } MyStruct; @interface StructTestingFile MyStruct *originalStruct; @end ``` Then from the .mm file, I call ``` originalStruct = loadTestInt(); ``` In the C file, here is what I'm doing: ``` extern "C" MyStruct* loadTestInt()...
You're creating a pointer but not allocating memory for the struct itself; ``` MyStruct *aStruct; aStruct = (MyStruct*)malloc(sizeof(MyStruct)); aStruct->test = 1; ```
Would this be the proper way to extend a structure array? ``` typedef struct { int x,y,z;} student_record; int main(){ student_record data_record[30]; // create array of 30 student_records num_of_new_records = 5; data_record = realloc(data_record,(sizeof(data_record) + (sizeof(student_record)*num_of_new_reco...
No - you can't assign to an array. Your code won't even compile - did you try it? If you want torealloc()you need to have usedmalloc()(or one of its relatives): ``` student_record *data_record = malloc(sizeof(student_record) * 30); ``` You probably shouldn't be assigning the return value ofrealloc()back to the ori...
I've got a function which is supposed to add a file to a node of a linked list, each file is a structure containing a constant char *name. The function uses parameters of a linked list and a const char[] (which will name of new data struct). Everything goes smoothly until I try to call the function again, the name of ...
Probablynew_namepoints the same buffer every time you call the function, so successive calls end up changing the old buffer which the old node still points to. You need to use malloc to allocate a new buffer each time.
I want to define a path like this: ``` #define PATH /abc/xyz/lmn ``` This PATH is a directory which has files foo1, foo2, foo3, ... foo115. How can I use this #define in the "open" call to open foo1, foo2, ... foo115 ? I want to basically do this using the directive: ``` fd = open("/abc/xyz/lmn/foo1", O_RDONLY); ...
``` #define PATH "/abc/xyz/lmn" int main (int argc, char **argv) { char file2open[256]; int i; for (i = 1; i <= 115; i++) { sprintf (file2open, "%sfoo%d", PATH, i); fd = open (file2open, O_RDONLY) ...... close (fd); } } ```
Assume I havea.hwhich includes the following: ``` <stdbool.h> <stddef.h> <stdin.h> ``` Assume I also haveb.hwhich also includes<stdbool.h>. Ifa.hhas the#ifndefpreprocessor definition statement in it andb.hdoesn't. Willa.hinclude only what hasn't been included inb.h? So whenb.hincludesa.h, willa.hincludestddef.handst...
All C standard headers must be made such that they can be included several times and in any order: Standard headers may be included in any order; each may be included more than once in a given scope, with no effect different from being included only once
Here is a very simple example of what I am trying to do: ``` #include <stdio.h> int main() { char a[2][2][5] = { {"hello", "world"}, {"again", "test1"}}; a[1] = a[0]; printf("a[0][0]: %s\n", a[0][0]); printf("a[0][1]: %s\n", a[0][1]); printf("a[1][0]: %s\n", a[1][0]); printf("a[1][1]: %s\n", a[1][1]); ...
You cannot assign arrays, you should copy them (using memcpy or memmove) ``` memcpy(a[1], a[0], sizeof(a[0])); ``` Also, each of your string is of size 6, not 5 (there is an implicit null terminator).
I was looking at a project that someone wanted done and in order to do it I need to edit Windows' Start Up Programs. I am unsure of where to begin looking. What I really need is just a reference to some Windows API functions that will let me do this. Thanks
Startup programs is just a directory, I don't think there are any specific functions for it. You should be able to create shortcuts inside and that should be it. ``` c:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\ ```
If I try to executes these commands: ``` int main(int argc, char* argv[]) { execl("/bin/echo","echo","list ","of", "files:\n",NULL); execl("/bin/ls","ls","-al",NULL); return 0; } ``` Only the first one gets executed, why?
execl REPLACES the current process - it's not a subroutine. You might try usingsystem()instead.
My professor showed us this code: ``` timerX(int x){ int times(int y){ return x * y; } return times; } ``` How does this work in C(using GCC compiler)? He said that as soon as the function disappears the inside function disappears? I appreciate any tips or advice.
It's called anested function, a GNU extension. Basically the inner function can acess the local variables of the outer function(the ones declared prior to its apparition)the inner function can only be called from outside via function poinyers but not after the containing function has terminated if the inner function ...
Is subtraction of pointers not pointing to different elements of same array valid in C? Is something such as below guaranteed to work according to C Standards? I vaguely remember reading that this is not valid? ``` int * a; int * b; a = (int*) 100; b = (int*) 200; printf("%d\n", b-a); ``` Will this give me 25.
From the C spec, Appendix J.2Undefined behaviour: Pointers that do not point into, or just beyond, the same array object are subtracted (6.5.6). 6.5.6 Additive operators, paragraph 9 says: When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the ar...
I'm having really hard time comprehending the syntax for function pointers. What I am trying to do is, have an array of function pointers, that takes no arguments, and returns a void pointer. Can anyone help with that?
First off, you should learn aboutcdecl:cdecl> declare a as array 10 of pointer to function(void) returning pointer to void void *(*a[10])(void )You can do it by hand - just build it up from the inside:ais an array:a[10]of pointers:*a[10]to functions:(*a[10])taking no arguments:(*a[10])(void)returningvoid *:void *(*a[1...
Global variables are initialized to "0" by default. How much difference does it make (if any) when I explicitly assign value "0" to it. Is any one of them faster/better/more optimized? I tried with a small sample .c program but I do not see any change in executable size. Edit:0I just want to understand the behavio...
The answer to your question is very implementation specific but typically all uninitialized global and static variables end up in the.bsssegment. Explicitly initialized variables are located in some otherdata segment. Both of these will be copied over by the program loader before the execution ofmain(). So, there shou...
How can I copy strings in C so that do not overlap the old values? I'd usedstrcpy()but it cleandestto set values ofsrc. ``` char* foo = " This is my string \0"; char* new = malloc(strlen(str) + 1); char* token; int size = 0; token = strtok(foo, " \t"); while( NULL != token ) { int i; for(i =...
How aboutstrdup? It even allocates the target buffer for you.
I have the below code which is supposed to exit if the provided user input is empty i.e they press [ENTER] when asked for the input. However it doesnt do anything if [ENTER] is pressed. ``` printf("Enter the website URL:\n"); scanf("%s", str); if(strlen(str) == 0) { printf("Empty URL"); exit(2); } ```
If the user just presses enter, the input will still contain a newline ('\n'). Your condition should be ``` if (!strcmp(str, "\n")) ```
I'm looking for the whole source code of all the C standard libraries. That said, I'm looking for the source code of stdio.h, stdlib.h, string.h, math.h, etc... I would like to see how they were created. I think that it depends from platform to platform, but Linux or Windows one will be welcomed.
If you want the actual implementations, as everyone else has assumed you don't, many Linux distributions currently useglibcto implement the C standard library. Common alternatives includemusl libc,diet libc,uClibc, andBionic
I am debugging a program using gdb. First Iloadmy executable, then Icontinueto run the program. I sometimes want to interrupt execution of my program, so I doCtrl + C. My problem is that this closesbothmy program and gdb. How can I exit my program without exiting gdb?
Have you tried to usekillfrom inside gdb?
In my code NVRAM is implemented as character device and I want to give a condition to check whether it is character device or not. How to implement it programmatically? How can I do it through c++ code. In terminal I gave commandcat /proc/devicesand it lists: ``` Character devices: 1 mem 4 /dev/vc/0 4 tty 4 ...
The number denotes the device's major number, and theCharacter devices:heading in that listing tells you it's a character device. If your character device is linked into the filesystem somewhere, like/dev/mydevice, you can also get information about it via thestatsystem call. Thest_modefield of thestruct statstructur...
How can I access theElementsof anIplImage(single channel and IPL_DEPTH_8U depth). I want to change the pixel value at a particular (x, y) position of the image.
opencv provide CV_IMAGE_ELEM method to access elements of IplImage,it's a macro, ``` define CV_IMAGE_ELEM( image, elemtype, row, col ) \ (((elemtype*)((image)->imageData + (image)->widthStep*(row)))[(col)]) ``` second parameter is the type of
I've seen parsers where the the handling of each keyword is controlled by an array of structures containing each keyword and function pointers to how to handle that keyword. What is this pattern called? Rather than trying to include a vague example here, I'll just point you to myproject.
It sounds very much likeTable-Driven parsing, which is generally employed byLR parsers.
This question already has answers here:Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer(5 answers)Closed4 years ago. ``` #include <stdio.h> #include <string.h> int main(void) { char *w; strcpy(w, "Hello Word"); printf("%s\n", w); return 0; } ``` What is wron...
You allocate no space for the string. w is just a pointer to some memory (garbage value since it's not initialized). ``` char w[32]; ``` or ``` char *w = malloc(32); ``` You need to allocated the space for the characters.
I'm tasked with changing a C program to x86 asm, and this line is confusing me: ``` int x; arr[100] ``` Full program: ``` int max = 100; int val = 0x7a; int x, arr[100]; /*I have a feeling that it is in fact a typo, and my compiler was just being nice*/ main(){ x = 1;/*I just got an email saying this was an error...
It is an array ofint. Before C99 in certain circumstances the type could be omitted in a declaration and thenintwas assumed. (Note that you are missing a;after the declaration of your array in your example). For example: ``` const x = 10; // valid in C89, not in C99 auto y = 10; // valid in C89, not in C99 `...
Here is a very simple example of what I am trying to do: ``` #include <stdio.h> int main() { char a[2][2][5] = { {"hello", "world"}, {"again", "test1"}}; a[1] = a[0]; printf("a[0][0]: %s\n", a[0][0]); printf("a[0][1]: %s\n", a[0][1]); printf("a[1][0]: %s\n", a[1][0]); printf("a[1][1]: %s\n", a[1][1]); ...
You cannot assign arrays, you should copy them (using memcpy or memmove) ``` memcpy(a[1], a[0], sizeof(a[0])); ``` Also, each of your string is of size 6, not 5 (there is an implicit null terminator).
I was looking at a project that someone wanted done and in order to do it I need to edit Windows' Start Up Programs. I am unsure of where to begin looking. What I really need is just a reference to some Windows API functions that will let me do this. Thanks
Startup programs is just a directory, I don't think there are any specific functions for it. You should be able to create shortcuts inside and that should be it. ``` c:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\ ```
If I try to executes these commands: ``` int main(int argc, char* argv[]) { execl("/bin/echo","echo","list ","of", "files:\n",NULL); execl("/bin/ls","ls","-al",NULL); return 0; } ``` Only the first one gets executed, why?
execl REPLACES the current process - it's not a subroutine. You might try usingsystem()instead.
My professor showed us this code: ``` timerX(int x){ int times(int y){ return x * y; } return times; } ``` How does this work in C(using GCC compiler)? He said that as soon as the function disappears the inside function disappears? I appreciate any tips or advice.
It's called anested function, a GNU extension. Basically the inner function can acess the local variables of the outer function(the ones declared prior to its apparition)the inner function can only be called from outside via function poinyers but not after the containing function has terminated if the inner function ...
Is subtraction of pointers not pointing to different elements of same array valid in C? Is something such as below guaranteed to work according to C Standards? I vaguely remember reading that this is not valid? ``` int * a; int * b; a = (int*) 100; b = (int*) 200; printf("%d\n", b-a); ``` Will this give me 25.
From the C spec, Appendix J.2Undefined behaviour: Pointers that do not point into, or just beyond, the same array object are subtracted (6.5.6). 6.5.6 Additive operators, paragraph 9 says: When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the ar...
I'm having really hard time comprehending the syntax for function pointers. What I am trying to do is, have an array of function pointers, that takes no arguments, and returns a void pointer. Can anyone help with that?
First off, you should learn aboutcdecl:cdecl> declare a as array 10 of pointer to function(void) returning pointer to void void *(*a[10])(void )You can do it by hand - just build it up from the inside:ais an array:a[10]of pointers:*a[10]to functions:(*a[10])taking no arguments:(*a[10])(void)returningvoid *:void *(*a[1...
Global variables are initialized to "0" by default. How much difference does it make (if any) when I explicitly assign value "0" to it. Is any one of them faster/better/more optimized? I tried with a small sample .c program but I do not see any change in executable size. Edit:0I just want to understand the behavio...
The answer to your question is very implementation specific but typically all uninitialized global and static variables end up in the.bsssegment. Explicitly initialized variables are located in some otherdata segment. Both of these will be copied over by the program loader before the execution ofmain(). So, there shou...
How can I copy strings in C so that do not overlap the old values? I'd usedstrcpy()but it cleandestto set values ofsrc. ``` char* foo = " This is my string \0"; char* new = malloc(strlen(str) + 1); char* token; int size = 0; token = strtok(foo, " \t"); while( NULL != token ) { int i; for(i =...
How aboutstrdup? It even allocates the target buffer for you.
I have the below code which is supposed to exit if the provided user input is empty i.e they press [ENTER] when asked for the input. However it doesnt do anything if [ENTER] is pressed. ``` printf("Enter the website URL:\n"); scanf("%s", str); if(strlen(str) == 0) { printf("Empty URL"); exit(2); } ```
If the user just presses enter, the input will still contain a newline ('\n'). Your condition should be ``` if (!strcmp(str, "\n")) ```
I'm looking for the whole source code of all the C standard libraries. That said, I'm looking for the source code of stdio.h, stdlib.h, string.h, math.h, etc... I would like to see how they were created. I think that it depends from platform to platform, but Linux or Windows one will be welcomed.
If you want the actual implementations, as everyone else has assumed you don't, many Linux distributions currently useglibcto implement the C standard library. Common alternatives includemusl libc,diet libc,uClibc, andBionic
I am debugging a program using gdb. First Iloadmy executable, then Icontinueto run the program. I sometimes want to interrupt execution of my program, so I doCtrl + C. My problem is that this closesbothmy program and gdb. How can I exit my program without exiting gdb?
Have you tried to usekillfrom inside gdb?
I have the following code: ``` int *pa; int a[3] = {1, 2, 3}; ``` Why pa = a is ok, but a = pa is not allowed?
The main difference is that type ofais still an array but it justdecaysinto a pointer when you dopa=a;.pawill now point to thefirstelement of the array not the entire array itself. When you doa=pait doesnot make any sense as you are trying point a datatype which is holding 3 integers to a type which can point only to ...
I am finding a way to implement a log mechanism that several processes write their behaviors (mainly for error and execution sequence of processes) to it by C with Linux? Just open a file that shared for multi-processes and let processes fprintf() to it? Any smart way to implement an option/mechanism that controls th...
Usesyslog, it's the standard (POSIX) logging solution.
How can i add a label next to a toolbar item in GTK+?For instance i want to show a save button and the text "Save" next to it like gedit or so.
gtk_action_set_is_important()if you're using GtkActions,gtk_tool_item_set_is_important()if you're using GtkToolItems.
I read on stackoverflow that when using the Windows API to start a thread_beginthreadex()is preferred overCreateThread(). I am creating threads like this usingCreateThread(): ``` DWORD WINAPI ThreadFunc(void* data) { // code for the thread functionality. } HANDLE Multicast = CreateThread(NULL, 0, ThreadFunc, N...
``` _beginthreadex(NULL, 0, ThreadFunc, NULL,0,NULL); ``` should do the trick for you. You can ignore those additional parameters as most of those are optional. The following SO links might be useful for you: Windows threading: _beginthread vs _beginthreadex vs CreateThread C++ _beginthread vs CreateThread
Here is the code that I have written to validate a BST. Is it correct? If not, how would I do this? ``` int validate(node *root) { if(root==NULL) return 1; else if(root->lchild!=NULL && (root->lchild)->data >=root->data) return 0; else if(root->rchild!=NULL && (root->rchild)->data <=root->data) return 0;...
Consider the Tree ``` 10 / \ 8 15 / \ / 3 9 4 ``` In this tree, everywhereroot->left->data < root->dataandroot->right->data > root->data. But the tree is not a BST as the node4is not at the right place (it's greater than10, which is not valid). If you have to validate the BST, you should be able to fig...
I expectuint32means "unsigned 32-bit integer". What does thetstand for?
The suffix_tdenotes atype name. For example,size_tis the type for size. Another popular line of thought regards it as a convention for namingtype definitions.
``` #include <signal.h> #include <stdio.h> void ints(int i ) { printf("ints \n"); } int main(void) { signal(SIGINT, ints); sleep(10); } ``` input Ctrl+C , the program will terminate immediately with output: ``` ^ints ``` I was wondering why,in my opinion,the program should terminate after 10 seconds ...
sleep() is one of those functions that is never re-started when interrupted. interestingly, it also does not return a EINT as one would expect. It instead returns success with the time remaining to sleep. See:http://www.kernel.org/doc/man-pages/online/pages/man7/signal.7.htmlfor details on other APIs that do not re...
For class, I have to write a basic proxy server in C. I need to test it with firefox, and I'm not sure how to do that. Say I have the server listening on port X-- how do I make firefox (on the same computer) send its requests there?
To enable sending localhost traffic to a proxy in recent versions of Firefox, openabout:config, search for "localhost", and setnetwork.proxy.allow_hijacking_localhostto true. This is in Firefox 71, and apparently was added around 67. Ran into it while trying to use Fiddler.
Im not "that" new to C but can some one please enlighten me on this one: ``` printf( "%d %d\n", sizeof( int ), sizeof( unsigned char ) ); ``` print as expected 4 and 1. ``` typedef struct { int a; unsigned char b; } test printf( "%d\n", sizeof( test ) ); ``` print 8... Im really confused!
Its called "alignment". Yourstructis padded. You can "pack" it (different compilers have different ways of defining which type should be packed), and then it won't be aligned, but you might have run-time data access issues.
Say I have declared a 2d array like ``` char* array[30][30]; ``` and what I am putting into it are strings, not all of length 30, like ``` char* string="test string"; ``` I want to put each char of string into array starting at array[i][0] I am trying to avoid using a loop to go over each character, is there a mo...
You mean like: ``` strcpy(array[i], string): ``` I assume you also meant to declare your 2D array with: ``` char array[30][30]; ```
How to fix this? Why the compiler claims of it if I am using the variable in another code parts? ``` void replace(char ** src, const char s, const char replace) { while(*(*src) != '\0') { if(* (*src) == s) { news[size] = replace; } else { news[size] = *(*src); } *(*src) ++...
When you do*(*src)++you're basically dereferencingsrc, then doing a postfix increment on the pointer,thendereferencing the pointer. It's a bug. You're not using the final value, which is why the compiler warns you. What you really want is(**src)++; i.e. dereference twice and then increment.
I am doing a c programming assignment where I am working with command-line arguments. One of the notes says that if the file you work with (to my understanding, it will always be "list.csv") is not yet created to create one. Just like vim does when you write "vim new.txt" and new.txt does not exist yet. I am just won...
you can use fopen(). the second parameter says, what to do. Read, create+write, append+create(if not existent) one way is to use fstat() on the filename. under UNIX try 'man fstat'
Can anybody give me a code which would return full path to System32 directory for Windows kernel driver?
You're lucky one.There's an open-source example that demonstrates exactly what you're looking for. AFAIK there's no equivalent to a function such asGetSystemDirectoryor whatever. However you may access the system-reserved file system objects by using symbolic links. directory using a symbolic link. The reserved sym...
I am stumped at this step while implementing a ternary tree: ``` #include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct tnode *Tptr; typedef struct node { char splitchar; Tptr lokid,eqkid,hikid; }Tnode; int research(Tptr p,char *s) { if (!p) return 0; if (*s<p-> } int main(){ ...
You've typedef'dTptras astruct tnode *, buttnodeis not defined or even declared. Perhaps you meant to name yournodestructtnodeinstead? BTW, there's an easy way to keep that from happening in the future... ``` typedef struct tnode { ... } Tnode, *Tptr; ``` At that point,Tptris always an alias to the correct ty...
Now i have this code, but it always set null ``` UNICODE_STRING str; char *cmp = "Hello"; RtlInitUnicodeString (&str, L"Hello world!"); if( ( strstr((char * )str.Buffer, cmp) ) != NULL) { // cmp founded in str. } else { // cmp not founded in str. Always here, but why?? } ``` Can you explain me why strstr in ...
You're searching for a multi-byte string in a Unicode one. Usewcsstr: ``` wchar * cmp = L"Hello"; wcsstr(str.Buffer, cmp); ``` You were hiding this by casting tochar *. You should really ask another question for your second request, but you might write a function like this: ``` void make_string_lower(WCHAR * str...
This is my c code: ``` #include <stdio.h> int main(){ int x[] = {6,1,2,3,4,5}; int *p=0; p =&x[0]; while(*p!='\0'){ printf("%d",*p); p++; } return 0; } ``` When run the output is 612345-448304448336 What are the digits after the minus sign and why is my code giving this?
The condition*p != '\0', which is the same as*p != 0, is never met because your array doesn't contain an element of value0, and thus you overrun the array bounds and step intoundefined behaviour. Instead, you should control the array range directly: ``` for (int const * p = x; p != x + sizeof(x)/sizeof(x[0]); ++p) ...
Suppose size of a block is 1X1 and I have to move in steps of 1/16 along both the x and y direction. I want to round 0.53124 to the nearest 1/16 of the size of the block which is 0.5625. And similarly I want to truncate 0.53124 to the nearest 1/16 of the size of the block which is 0.5. Is there an efficient way of doi...
Simplest way in most situations and languages would to be to multiply by 16round to the nearest integerdivide by 16.
This is probably very simple, but I am trying to make something with has a variable defined like this: ``` char *temp[50]; ``` And to change it I am doing things like: ``` strcpy(temp[1],"Hi"); ``` However this segmentation faults. I tried&temp[1], however this does not work. Could anyone point me in the right dir...
You only created an array of pointers that point to nothing in particular. You need to assign memory totemp[1], possibly viamalloc,beforestrcpy. ``` temp[1] = malloc(3); /* Hi\0 */ ```
``` printf("%.2lf\n",odd); //(1) printf("%.2lf\n",37.975); //(2) printf("%.2lf\n",(odd*0.65 -1)*2); //(3) printf("%.3lf\n",(odd*0.65 -1)*2); //(4) ``` Below is the output: 30.75 37.98 37.97 37.975 Why the output of expression(3) is not ...
This is likely due to floating point rounding errors. The result of(odd * 0.65 - 1) * 2is likely37.97499999999999or something close to (but less than)37.975. By the usual rounding rules, this is rounded down to37.97in the output.
This question already has answers here:Closed11 years ago. Possible Duplicate:Sizeof doesn't return the true size of variable in CC -> sizeof string is always 8 Sizeof prints out 6 for: ``` printf("%d\n", sizeof("abcde")); ``` But it prints out 4 for: ``` char* str = "abcde"; printf("%d\n", sizeof(str)); ``` Can...
The string literal"abcde"is a characterarray. It is 6 bytes long, including the null terminator. A variable of typechar*is apointerto a character. Its size is the size of a pointer, which on 32-bit systems is 4 bytes.sizeofis a compile time operation†, so it only looks at the variable's static type, which in this c...
I have the following binary number ``` uint64_t = 0b0100; ``` And I want to negate it to ``` 0b1011 ``` This is a specific example but I want it to work for any binary number variable. For example, uint64_t a So is there a function like negate that would make the following true ``` a == negate(negate(a)); ```
Simply use thebitwise negation operator: ``` bar = ~bar ```
Looking at the man page forfopenI cannot get a definite answer to this question. ``` FILE *fopen(const char *path, const char *mode); ``` I understand thatfopenreturns a file pointer to a stream but is a file descriptor created as a byproduct? I am trying to make sure that I include the flagFD_CLOEXECon every instan...
On Unix (which I assume you're using because you're mentioningfcntl) itdoesopen a file descriptor, asfopen(3)eventually callsopen(2).You can get that file descriptor viafileno(3).
I have multiple C programs each doing the same piece of functionality. I want to evaluate/calculate which of these has a lower power consumption( on ARM) Is there some tool(simulator) with which I can simulate and get the number of power consumed and compare the same for each of the programs on desktop? Based on this...
that is not something you can simply model and run, you would have to know the exact core and gate switches, etc and the apply that to the cell library and on and on. If you work with/for the company making the chip then ask the silicon team they might have a tool for that otherwise you have to measure power differenc...
I have download the source code of gcc, using this command: ``` svn checkout svn://gcc.gnu.org/svn/gcc/trunk SomeLocalDir ``` Who can tell me where can I find the implementation of standard library function strncpy()? Thank you.
These answers are correct, in that a standard C library will implementstrncpy.However, gcc hasbuiltinfunctions that may be generated by the compiler - as intermediate code, not linked function calls - of whichstrncpyis one. These can be explicitly disabled with-fno-builtin. In the gcc source tree, you can find the co...
This question already has answers here:Closed11 years ago. Possible Duplicate:What is a fast C or Objective-C math parser? I have a NSString which represents a calculation eg.@"(10+10)*2"and I want to evaluate the string as if it was actually something like this; ``` double result = (10+10)*2; ``` What is the most...
Take a look at Dave DeLong'sDDMathParser framework.
I was wondering why thissize_tis used where I can use say int type. Its said thatsize_tis a return type ofsizeofoperator. What does it mean? like if I usesizeof(int)and store what its return to aninttype variable, then it also works, it's not necessary to store it in asize_ttype variable. I just clearly want to know t...
size_tis guaranteed to be able to represent the largest size possible,intis not. This meanssize_tis more portable. For instance, what ifintcould only store up to 255 but you could allocate arrays of 5000 bytes? Clearly this wouldn't work, however withsize_tit will.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. I want to develope a firewall for L...
You can start by using the Netfilters API (http://www.netfilter.org/). I think it is a good starting point for packet filtering. I've worked a lot with this API in kernel space. I'm not sure if there is a library for user land, but I must tell you that it's pretty easy to develop something with netfilters in the kerne...
This is my c code: ``` #include <stdio.h> int main(){ int x[] = {6,1,2,3,4,5}; int *p=0; p =&x[0]; while(*p!='\0'){ printf("%d",*p); p++; } return 0; } ``` When run the output is 612345-448304448336 What are the digits after the minus sign and why is my code giving this?
The condition*p != '\0', which is the same as*p != 0, is never met because your array doesn't contain an element of value0, and thus you overrun the array bounds and step intoundefined behaviour. Instead, you should control the array range directly: ``` for (int const * p = x; p != x + sizeof(x)/sizeof(x[0]); ++p) ...
Suppose size of a block is 1X1 and I have to move in steps of 1/16 along both the x and y direction. I want to round 0.53124 to the nearest 1/16 of the size of the block which is 0.5625. And similarly I want to truncate 0.53124 to the nearest 1/16 of the size of the block which is 0.5. Is there an efficient way of doi...
Simplest way in most situations and languages would to be to multiply by 16round to the nearest integerdivide by 16.
Looking at the man page forfopenI cannot get a definite answer to this question. ``` FILE *fopen(const char *path, const char *mode); ``` I understand thatfopenreturns a file pointer to a stream but is a file descriptor created as a byproduct? I am trying to make sure that I include the flagFD_CLOEXECon every instan...
On Unix (which I assume you're using because you're mentioningfcntl) itdoesopen a file descriptor, asfopen(3)eventually callsopen(2).You can get that file descriptor viafileno(3).
I would like tofscanffrom a stream containing data likeABCD0000intounsigned shortvariables. What is the proper format specifier for that? I was unable to find any way of combining both "unsigned" and "hexadecimal" with theh(short) specifier. Take for instance ``` #include <stdio.h> unsigned short hex_input; char b...
Should behxstill. (Hexadecimal is handled as unsigned by default.) Also note that your example ofABCD0000will only have its lower four nybbles read into an unsigned short, so you'll end up getting a value of0.
Is there any macro or function to construct a float (double) from a given sign, mantissa and exponent (all binary or decimal) that either returns a valid float (double) number or returns NaN if the number specified by input is not representable as float (double)?
The function you're looking for isldexp.
Right now I have this ``` #include <zlib.h> int main () { puts (ZLIB_VERSION); } ``` As an exercise, is there any way I could get it to compile on one line, something like ``` #include <zlib.h>; int main (){ puts (ZLIB_VERSION); } ``` I can get it to compile on two lines, but the include is preventing one line...
There's no way to do exactly what you want. With that said, if this is part of a build system, it would bea lotbetter to use the-Eoption to the compiler to preprocess a file containing simply ``` #include <zlib.h> ZLIB_VERSION ``` and then parse the output. This way you avoid running a program generated by the compi...
I have a file like this: ``` 10 15 something ``` I want to read this into tree variables, let's say number1, number2, and mystring. I have doubts about what kind of pattern to give to fscanf. I am thinking something like this; ``` fscanf(fp,"%i %i\n%s",number1,number2,mystring); ``` Should this work, and also, is ...
``` fscanf(fp,"%i %i\n%s",&number1,&number2,mystring); ``` fscanftakes pointers.
I need to use some part of a jpeg image (a rectangle in the center) decompressing it up to DCT coeficients. Is this possible with libjpeg , or some other open source tool ?
What you're asking to do is non-standard use case. It is unlikely any open source library will have this feature built-in. It shouldn't take major modifications to get the data you need. How much effort are you willing to provide and how much do you understand the JPEG standard and the library you're using? If your r...
If I have this functionfoo()and I'm calling it from another functionfoo2(); must I free the memory in the calling function like this? ``` char *foo(char *str1){ char *str2; str2 = malloc((sizeof(char) * strlen(str1)) + 1); memcpy(str2, str1, strlen(str1) + 1) return str2; } void foo2(void){ char ...
Yes, except you don't test that your malloc is successful
I have the following code in C: ``` int l; short s; l = 0xdeadbeef; s = l; ``` Assuming int is 32 bits and short is 16 bits, when performing s = l, s will be promoted to 32 bits and after assignment, only lower 16 bits will be kept in s. My question is that when s is promoted to 32 bits, wil...
Actuallysis not promoted at all. Sincesis signed andlis too large to fit ins, assigning l to s in this case is implementation defined behavior. 6.3.1.3-3Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is rai...
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
For hex numbers, you can usesprintf: ``` char buff[80]; sprintf(buff, "0x%02x", 64); ```
I have a path, for example, named /my/path/test/mytestpath , and I want to judge if it start with a given path, for example /my/path
TheC++17 filesystem libraryis probably the most robust solution. If C++17 is not available to you,Boost.Filesystemprovides an implementation for earlier C++ versions. Try something like: ``` bool isSubDir(path p, path root) { while(p != path()) { if(p == root) { return true; } ...
I have written the following simple C code, which compiles and runs fine. However it behaves in a way that I don't understand. I type a character, it prints it on the screen. Butwhen I press the return key it prints the whole line. So if I type the letters a, b and c, abc is printed on the command line twice. WHy does...
Because your terminal is line buffered. It doesn't send data to your program until it encounters a newline, though it will echo the character to the screen so you can see they key you hit.
Im trying to write some user input to a file in binary format. When I look at the file im expecting to see only 0 and 1's, but output to the file is printed in normal text: ``` FILE *f; char array[8]; f = fopen("numbers.bin", "ab+"); if(f==NULL){ printf("Could not open file!\n"); system("p...
since you read the input as string (gets), this is how the data is written later. You need to usescanfto read the numbers. ``` int num; scanf("%d", &num); fwrite(&num, sizeof(int), 1, f); ```
I compiled a program with a static librarylibpolarssl.a I would like to create aREADMEwith the library version. Is there aprogrammaticway to get the version of this library?
Polar SSL has an internal version number and the wrappers to export it to your application, see: http://polarssl.org/apidoc/version_8h.html ``` // Get the version number unsigned int version_get_number(void); // Get the version string ("x.y.z") void version_get_string(char *string); // Get the full version string ...