question
stringlengths
25
894
answer
stringlengths
4
863
I have this struct in C: ``` typedef struct Set { unsigned int state : 1; char array[LEN]; } Set; ``` While this compiles and executes I noticed that the bit-field actually alters one bit in the char array itself! So it I'm wondering if this is some known issue and it is bad practice to have bit-fields with ...
Hogwash! Rest assured that elements of astructarealwayslaid out so they are disjoint in memory. You program clearly has a construct that is causingundefined behaviour- most likely you are indexingarray[-1]or similar. (Unless some smart alec has written#define struct union: the behaviour of that is also undefined si...
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed6 years ago.Improve...
This is how you should do it. ``` #include <stdio.h> int main(){ for(int e = 0; e < 253; e++) { printf("a"); } printf("\n"); return 0; } ```
I've been learning C recently. I have difficulty understanding the result of the code below. Why isb255 at last? ``` unsigned char a=1; int b=0; do { b++; a++; }while(a!=0); ```
Anunsigned charcan only take values between 0 and 255. In your code, at each iteration of the loop,aandbboth get incremented by 1 untilareaches 255. Whenais 255 and should be incremented by 1 more, it would have been 256 but since anunsigned charcan only take values between 0 and 255,atakes the value 0 instead of 256....
For the purpose of my school, I am learning how to do a raycast in C. Based on this tutorial I foundhttp://permadi.com/1996/05/ray-casting-tutorial-7/, the author explains his method to find deltaX and deltaY to check whenever there is a wall at a position based on deltaX or deltaY. However he's getting deltaX and d...
At 0 and pi, there's no point in searching for horizontal intersections as the ray is horizontal. You'll need to explicitly check for that case. At pi/2 and 3pi/2, the tangent is infinite so 1/tan() should give you zero with floating point math. It will work even if it looks ugly. For vertical intersections, shift t...
What is a recommended methodology / library for accurate benchmarking of C / C++ code? Something that would overcome the inaccuracies of simply measuring execution time, i.e. that CPU frequency and system load may change across execution times. Not sure if counting executed instructions is the correct approach, becaus...
GNU profiler, gprof, is a traditional way of doing performance measurements for a signle-threaded code. You do not have to instrument the code manually, just add an option to gcc during build.
I have this struct in C: ``` typedef struct Set { unsigned int state : 1; char array[LEN]; } Set; ``` While this compiles and executes I noticed that the bit-field actually alters one bit in the char array itself! So it I'm wondering if this is some known issue and it is bad practice to have bit-fields with ...
Hogwash! Rest assured that elements of astructarealwayslaid out so they are disjoint in memory. You program clearly has a construct that is causingundefined behaviour- most likely you are indexingarray[-1]or similar. (Unless some smart alec has written#define struct union: the behaviour of that is also undefined si...
I have a pointer to a string which is "unsigned char *" and i want to use it as an argument in strncmp() function. But compiler complains: ``` invalid conversion from 'unsigned char*' to 'const char*' ``` How can i make: ``` strncmp(const char *a, unsigned char *b, size_t size); ``` work? Is there any workaround?...
You can safely cast unsigned into signed. ``` unsigned char * p2 = ...; strncmp(px, (char *)p2, 5); ``` should work. ``` unsigned char * p2 = ...; char * p3 = static_cast<char *>(p2); ``` This maybe overkill.
This question already has answers here:Address of array VS pointer-to-pointer : Not the same?(2 answers)Closed6 years ago. Consider the below code snippet: ``` int x[] ={10,20,30,40,50}; int *p; int **q; p = x; /* Obviously p now holds base address of array. So no problem here */ q = &x; /* Error. Why? */ ```...
An array decays to a pointer in certain contexts, like assignment, or passing it to a function. The address-of operator,&, does not decay the array into a pointer. It's as simple as that. Instead, you get a pointer to the array. In this case: ``` int (*q)[5]; q= &x; // Works just fine ```
I'm compiling an app using quake qgl api on X11/FreeGLUT (OSX 10.12) Compilation fails with errors like this: ``` /ref_gl/qgl.h:579:8: error: unknown type name 'PFNGLTEXIMAGE3DEXTPROC'; did you mean 'PFNGLXBINDTEXIMAGEEXTPROC'? extern PFNGLTEXIMAGE3DEXTPROC glTexImage3DEXT; ``` Seems that external ...
Don't use X11 on MacOS. X11 is not the native graphics system of MacOS and the X11 server that comes with MacOS does not have advanced OpenGL support. Use the native MacOS OpenGL framework.
Scenario 1 ``` char string[MAX_BYTES] = "This is a string\nthat I'm using\nfor scenario 1"; ``` Scenario 2 ``` printf("Enter string: "); fgets(string, MAX_BYTES, stdin); ``` If I provide the string in-code (scen. 1), I can line break with '\n'. But if prompting in terminal withfgets()orscanf()(scen. 2), pressinge...
Usually that can't be done withfgetsandscanf, but you can usegetcharinstead: ``` int ch; int idx = 0; while( ( (ch = getchar()) != EOF ) && idx < MAX_BYTES) { string[idx++] = ch; } printf("%s", string); ``` Notegetcharwill accept any input including\nand thewhileloop terminates whenEOFieCtrl+Dfromstdin. You then...
I am trying to do this: ``` void main(int argc, char *argv[]){ int mode,f; mode = atoi(argv[2]); if((f = open("fichero.txt",O_CREAT, mode))==-1){ perror("Error"); exit(1); } } ``` However, when I introduce a number like 0664, mode equals 664. How can I keep that leading zero?
Theatoifunction assumes the string is the decimal representation of a number. If you want to convert from different bases, usestrtol. ``` mode = strtol(argv[2], NULL, 0); ``` The third argument specifies the number base. If this value is 0, it will treat the string as hexadecimal if it starts with0x, octal if it s...
I defined a pointer to a function type: ``` typedef uint32_t (*funct_t)(bool); ``` I declared a function that uses the same interface: ``` uint32_t a_funct(bool); ``` I need to use the pointer to a function type instead. How can I do that?
If you define the typedef like this: ``` typedef uint32_t (funct_t)(bool); // note the missing * before the type name ``` You can declare the function like this: ``` funct_t a_funct; ``` Note that when you define the function, you still need to spell out the parameters. ``` uint32_t a_funct(bool x) { ... } ...
This question already has answers here:Opposite of C preprocessor "stringification"(3 answers)Closed6 years ago. I know that it is possible to convert something to string with macro like this: ``` #define STRING(s) #s printf("%s", STRING(i am string)); ``` But it is possible to do the opposite? ``` #define MyType...
AFAIK, it is not possible using the standard C preprocessor. What you want is not part of the standard C11 (or C99) language. And neither part of C++11 or C++14 (which is a different language than C). But you might use some different preprocessor or some script to transform your weird source file into some C file. Y...
I have a pointer to a string which is "unsigned char *" and i want to use it as an argument in strncmp() function. But compiler complains: ``` invalid conversion from 'unsigned char*' to 'const char*' ``` How can i make: ``` strncmp(const char *a, unsigned char *b, size_t size); ``` work? Is there any workaround?...
You can safely cast unsigned into signed. ``` unsigned char * p2 = ...; strncmp(px, (char *)p2, 5); ``` should work. ``` unsigned char * p2 = ...; char * p3 = static_cast<char *>(p2); ``` This maybe overkill.
This question already has answers here:Maximum size of a bit field in C or C++? [duplicate](2 answers)struct bitfield max size (C99, C++)(4 answers)Closed6 years ago. Is the following code legal? ``` struct BigInt { uint64_t a : 128; }; ```
A bitfield must fit within a singleint, so you're out of luck unlessintis 128 bits on your platform. (You were also missing a;at the end of thestructprior to the edit.)
First of all, I am aware that what I am trying to do might be outside the C standard. I'd like to know if it is possible to make auint4_t/int4_toruint128_t/int128_ttype in C. I know I could do this using bitshifts and complex functions, but can I do it without those?
You can use bitfields within a structure to get fields narrower than a uint8_t, but, the base datatype they're stored in will not be any smaller. ``` struct SmallInt { unsigned int a : 4; }; ``` will give you a structure with a member called a that is 4 bits wide.
We are using C89 on an embedded platform. I attempted to print out asize_t, but it did not work: ``` #include <stdio.h> int main(void) { size_t n = 123; printf("%zu\n",n); return 0; } ``` Instead of123, I gotzu.Other specifiers work correctly. Ifsize_texists shouldn'tzualso be available inprintf?Is this...
If size_t exists shouldn't zu also be available in printf? size_texisted at least since C89 but the respective format specifier%zu(specifically the length modifierz) was added to the standard only since C99. So, if you can't use C99 (or C11) and had to printsize_tin C89, you just have to fallback to other existing ...
I need to get the sum of a list that only contains doubles. For some reason that doesn't work, though: ``` double sum(DoubleList* list) { DoubleNode *next = NULL; double sum = 0; for (DoubleNode *n = list->first; n != NULL; n = next) { sum += n->value; } return sum; } ```
You should fix your loop as follows. ``` double sum(DoubleList* list) { double sum = 0; for (DoubleNode *n = list->first; n != NULL; n = n->next) { sum += n->value; } return sum; } ``` The sample code above assumes DoubleNodehasan attribute named next and is of type DoubleNode*, that stores t...
I have a very simple program in C: ``` #include <stdio.h> int main() { char c; int i; if( (c = getchar()) == 'a') printf("pressed a"); return 0; } ``` I would like to printaexactly after a user pressedahowever this is printed only after I press enter. I need to write a much more complicated program wh...
I would like to print a exactly after a user pressed a You cannot do it without using third party libraries, as the cin file, if it is a terminal, receives data only after the user presses enter. You may use some branch ofcurses.
I am compiling a driver for MIPS architecture on 4.4 kernel. It seems compiler is not including ``` /linux-4.4.34/include/linux/types.h ``` but instead it includes ``` /linux-4.4.34/include/uapi/linux/types.h ``` Because of this I see below error.I did not include the path/linux-4.4.34/include/uapiin driver makefi...
In mipsisa32-be-elf.inc file, given the path /kernel/include/uapi in -isystem compilation flag. This helps to solve the above compilation issue.
I have one program that uses shared library. In shared library, error case they have written exit(0). So if that function is called then exit(0) will be executed of shared library. Will it exit my program too ?
Yes it terminates the calling process immediately.SIGCHLD signal will be send to process which inherited by process 1 or init.
Ifreememory about3Gand then usemalloc_trim(0)to return heap memory to system and watching resident memory usage withtop. But the resident memory doesn't decrease. These memory ismalloc()ed every time for about54Kwhich is less than128K. And it ismalloc()ed withbrk()system call.
According toits docs, Themalloc_trim()functionattemptsto release free memoryat the top of the heap (emphasis added). It cannot release memory that has allocated memory above it on the heap, and therefore it does not guarantee to return anything to the system. I'm inclined to think that little, if any, of the memor...
This question already has answers here:Is floating point math broken?(33 answers)Closed6 years ago. On a 32-bit system, I found that the operation below always return the correct value when a < 2^31 but returns random results where a is larger. ``` uint64_t a = 14227959735; uint64_t b = 32768; float c = 256.0; uint6...
The entire calculation goes to float, then gets cast to a 64 bit integer. But floats can't accurately represent large integers, unless they happen to be powers of two.
I got a warning: ``` assignment makes integer from pointer without a cast. ``` The line that triggers the warning is: ``` nev[i][0]=""; ``` Thenevvariable is a 2 dimension char block(please don't ask why, I don't know). Thanks in advance guys!
Ifnevis a 2-dimensional array ofchar, thennev[i][0]is achar. But""is an array ofchar, not achar. – Barmar nev[i][0]="";-->nev[i][0]=0;– BLUEPIXY
I was given the program below in an exam and the question was how many kill signals must be sent to the process in order to terminate it. My answer was 3 signals, but the professor insisted on only 2 signals are needed to terminate the process? How is so? ``` static void action(int sig) { signal(SIGINT,SIG_DFL); ...
You need to send SIGUSR1 to invoke theaction. And allactiondoes is set SIGINT to its default signal handler (SIG_DFL). Then you send the SIGINT, that then triggers the default handler which terminates the process. NOTE:It must be done in that order, any attempt to send SIGINT before SIGUSR1 will be ignored because of...
As a programmer I've been taught to prefer the keywordinlineto macro definitions for small functions. I know that inline is known to be more safe due to macro definitions doing no type checking, however I am told that inline is only a request for the compiler to actually replace the code, and the compiler doesn't have...
Macros are textual replacements performed before the compilation step - they cannot have "run-time overhead" in the way a function call could. Still, this is not a good reason to use macros instead of functions, as compilers will automatically inline functions even without theinlinekeyword with optimizations enabled. ...
Is there any way to have a simple edit box in plain X11 C or C++ code? By "plain X11 C or C++ code" I mean creating the control on aXCreateSimpleWindowcreated window as theCreateWindow("edit"..)equivalent in Win32 API. If not, what are my options to have a simple edit box with the minimum amount of dependencies (i.e...
Plain X11 doesn't have such functionality - It is alow-level windowing toolkit(opening and maintaining windows, receiving input events, drawing to windows). In case you are prepared to write such an edit window from the available primitives, you are fine. If not, you need to use some toolkit that does it for you. The...
Can a user type null terminator in an input, for which scanf is used, so the length of the input would be 0? ``` char msg[1000]; scanf("%1000s",msg); // the user would type nothing: '' or '\0' ```
On many systems, the answer is "Yes". Usually, the magic sequence isControl-@. The character code for @ is usually 64, one less the that of A (65). Control-A is character code 1; one less is character code 0, aka'\0'. Note that to get a zero-length input, you'd have to type the null byte as the first non-space ch...
After a call ofGetOpenFileNamethe current directory of the process changes to the directory of the file opened file by theGetOpenFileName. How can I keep the default current directory instead ?
How can I keep the default current directory instead ? If you read theOPENFILENAMEdocumentation, there is anOFN_NOCHANGEDIRflag for that exact purpose: Restores the current directory to its original value if the user changed the directory while searching for files. Despite what the documentation claims, this flag i...
As the title suggests, I would like to create connection between a JavaScript (usingWebSocket) client and a C/C++ (usingWinsock) server. A simple code example would be much appreciated.
You can't use Websocket at java side and a Winsock only implementation on C++ side, you have to implement Websocket over winsock or using some thing like Qt Platform which has an implementation Websocket under C++. sample codes are available onQt Docs.
I'm trying to read from terminal a few lines of text with fgets. The problem is it only read one line and stops. I tried flushing buffer and using getchar to absorb the newline but it still didn't work. ``` #include <stdio.h> int main() { int count = 2; int len = 5; char str[count][len]; ...
fflush(stdin);isundefined behaviour. Don't use it. I think, your problem is that you are inputting the morelencharacters and thus the second call tofgets()reads in the character left by the first call. Just increaselensufficiently. You should also check the return value offgets()for failure.
I have a Linux program, that from time to time ends with a segmentation fault. The program is running periodically every hour, but the segmentation fault occurs only sometimes. I have a problem to debug this, because if I run the program again with the same input, no error is reported and all is OK. Is there a way, ...
The usual way is to have the crashing program generate a corefile and analyze this after the crash. Make sure, that: the maximum corefile-size is big enough (i.e.unlimited) by callingulimit -c unlimitedin the shell, which starts the process.The cwd is writable by the segfaulting process. Then you can analyze the fil...
Is there an easy way to do the following: Convert a byte array like so{1,3,0,2,4}to achararray like so{'1','3','0','2','4'}or"13024". I can do the following ( I think ) but it is more cumbersome: ``` itoa(byte_arr[0],cap_periph[0],10); itoa(byte_arr[1],cap_periph[1],10); itoa(byte_arr[2],cap...
The main point is to use a loop, whatever implementation you use. If you are totally sure that each element inside source array is between 0 and 9: ``` // Only works if each element of byte_arr is between 0 and 9 for(int i = 0; i < 3; ++i) { cap_periph[i] = byte_arr[i] + '0'; } cap_periph[3] = '\0'; ```
Is it safe to share an aligned integer variable, not bigger than the processor natural word, with volatile qualifier, between the main program and an ISR in C? Is it guaranteed that no torn reads or writes may happen?
Thevolatilekeyword does not imply atomicity - that simply ensures that a variable is explicitly read and not assumed not to have changed. For safe shared access without any other protection mechanism the variable must be both atomic and declaredvolatile. The compiler may document types that are atomic for any partic...
I would like to ask: withA,B, andCare any binary number. After gettingC = A & B(&isANDoperator), is there any possibility to recoverAfromBandC? I know that the information ofAwill be lost through the operation. Can we form a function likeB <...> C = A, and how complexity it can be? For example: ``` A = 0011 B = 101...
No, it's not possible. You can see this from the truth table for AND: ``` A B C (A & B) 0 0 0 0 1 0 1 0 0 1 1 1 ``` Suppose you know that B is 0 and C is 0. A could be either 1 or 0, so it cannot be deduced from B and C.
How can i use a variable(that I would get from user input) to call a function ? ``` char user_function[10]; scanf("%s", user_function); user_function(); //Calls the function named user_function that the user typed ``` (without having something like this) ``` char user_function[10]; scanf("%s", user_function); if( s...
You can't. At some point you have to look at the string contents and use those to call a particular function. You can "hide it" a bit by doing something like a lookup table/hashmap of strings to function pointers, but in the end it is still just "look at the string and decide what to call"
In my program I have got a NxN table stored in one-dimensional table. So, I use#define Board(x,y) board[(x)*N + (y)]and works perfectly So, what if my board becomes N1xN2 and N1 is different than N2? How should I set the #define instruction then? thank you in advance
It shouldn't work perfectly. You need(board[(x)*N+(y)])for square boards, and(board[(x)*N2+(y)])for non-square boards, assuming x from 0 to N1-1, y from 0 to N2-1
In my program I have got a NxN table stored in one-dimensional table. So, I use#define Board(x,y) board[(x)*N + (y)]and works perfectly So, what if my board becomes N1xN2 and N1 is different than N2? How should I set the #define instruction then? thank you in advance
It shouldn't work perfectly. You need(board[(x)*N+(y)])for square boards, and(board[(x)*N2+(y)])for non-square boards, assuming x from 0 to N1-1, y from 0 to N2-1
This question already has answers here:C Unions output unclear(2 answers)Closed6 years ago. I was at an interview and the following code was given to me:- ``` union mix { int i; char c[2]; }; int main() { union mix key; key.i=512; printf("\n %d,%d,%d",key.i,key.c[0],key.c[1]); return 0; }...
It's a union, meaningiandcoccupy the same memory.512 is 0x200, meaning first byte is zero, second is 2 (each byte takes two hex digits).This of course depends on the endianness of your CPU.
I know, that I can 'close' an X11 Window by calling: ``` XDestroyWindow(display, id); ``` The problem is, this destroyes the window immediately. On the other hand, if i click the close button (x in the title bar) the app can show something like "Do you really want to exit?". So how can I emulate this type of window...
I found a solution: ``` XEvent event; event.xclient.type = ClientMessage; event.xclient.window = id; event.xclient.message_type = XInternAtom(d, "WM_PROTOCOLS", TRUE); event.xclient.format = 32; event.xclient.data.l[0] = XInternAtom(d, "WM_DELETE_WINDOW", FALSE); event.xclient.data.l[1] = CurrentTime; XSendEvent(d, i...
I wrote an app that changes the Windows wallpaper by registry, but I need to notify Explorer.exe so I can see the new background. I tried usingSendMessageTimeoutW: ``` SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0, 0, SMTO_ABORTIFHUNG, 5000, NULL); ``` However, it di...
Don't modify the windows registry directly for this kind of settings; the correct way to modify the wallpaper is to call theSystemParametersInfoAPI, passingSPI_SETDESKWALLPAPER, passing the path to the wallpaper inpvParamandSPIF_UPDATEINIFILE | SPIF_SENDCHANGEinfWinIni(which makes the modification permanent).
What happens when I put a pointerint*as parameter where the parameter type is a pointer of pointersint**? ``` int main(..) { int* local_arr = malloc( 10 * sizeof(int) ); func(local_arr) } void func(int** par) {...} ```
Passing anint *parameter for anint **argument without an explicit cast is aconstraint violationin C. C language does not support implicit conversion ofint *value toint **type. Your program is not a valid C program and the compiler is required to tell you about it through diagnostic messages. In other words, this is w...
I know, that I can 'close' an X11 Window by calling: ``` XDestroyWindow(display, id); ``` The problem is, this destroyes the window immediately. On the other hand, if i click the close button (x in the title bar) the app can show something like "Do you really want to exit?". So how can I emulate this type of window...
I found a solution: ``` XEvent event; event.xclient.type = ClientMessage; event.xclient.window = id; event.xclient.message_type = XInternAtom(d, "WM_PROTOCOLS", TRUE); event.xclient.format = 32; event.xclient.data.l[0] = XInternAtom(d, "WM_DELETE_WINDOW", FALSE); event.xclient.data.l[1] = CurrentTime; XSendEvent(d, i...
I wrote an app that changes the Windows wallpaper by registry, but I need to notify Explorer.exe so I can see the new background. I tried usingSendMessageTimeoutW: ``` SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0, 0, SMTO_ABORTIFHUNG, 5000, NULL); ``` However, it di...
Don't modify the windows registry directly for this kind of settings; the correct way to modify the wallpaper is to call theSystemParametersInfoAPI, passingSPI_SETDESKWALLPAPER, passing the path to the wallpaper inpvParamandSPIF_UPDATEINIFILE | SPIF_SENDCHANGEinfWinIni(which makes the modification permanent).
What happens when I put a pointerint*as parameter where the parameter type is a pointer of pointersint**? ``` int main(..) { int* local_arr = malloc( 10 * sizeof(int) ); func(local_arr) } void func(int** par) {...} ```
Passing anint *parameter for anint **argument without an explicit cast is aconstraint violationin C. C language does not support implicit conversion ofint *value toint **type. Your program is not a valid C program and the compiler is required to tell you about it through diagnostic messages. In other words, this is w...
I've seen two different ways to fill achar[]with0(in this example, upon initialization): ``` /* method 1 */ char foo[1024] = {0}; /* method 2 */ char foo[1024]; memset(foo, '\0', sizeof(foo)); ``` What are the main differences between the two codes? How do they differ in functionality, etc?
What are the main differences between the two codes? In case 1 the array is zeroed out from the moment it can be used, as it gotinitialised. In case 2 its content is well defined only after the call tomemset(). The essential difference is that for case 2 there is is gap wherefoo's content is "garbage". This isn't t...
This question already has answers here:Create a directory if it doesn't exist(10 answers)Closed6 years ago. I am looking to make a program using CreateDirectory(), RemoveDirectory(), and similar functions. One of the possible return errors from these commands ERROR_ALREADY_EXISTS. I want an if statement to catch this...
You need to callGetLastError ()and check to see if the error condition meetsERROR_ALREADY_EXISTS; after callingCreateDirectory()and when it returns 0.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed6 years ago.Improve this question I've been told this code snippet is equivalent to(int)sqrt(n) ``` int s(int n) { ...
It uses the fact thatx^2 = 1 + 3 + 5 + ... + (2*x-1). Hereigoes over the odd numbers andkis their sum. It stops when the sum is more thann. At this pointi == (2*x-1) + 2wherexis the square root, sox == floor(i/2).
I'm creating a small unix shell, execve has an issue withsed. When I executesed -e 's/Roses/Turnips/'the command fails with execve. ``` #include <unistd.h> #include <stdio.h> #include <fcntl.h> int main(int ac, char **av, char **envp) { char *argv[] = { "/usr/bin/sed", "-e", "'s/Roses/Turnips/'", 0 }; execve...
Get rid of the single quotes around thes///argument. Those are part of shell syntax, notsedsyntax. ``` char *argv[] = { "/usr/bin/sed", "-e", "s/Roses/Turnips/", 0 }; ``` execveexecutes the program directly, it doesn't use a shell. Every argument is sent literally to the program, so no escaping or quoting is needed ...
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.Closed6 years ago.Improve this question For my assignment, I've to write a function to create a directory but I'm not allowed to use SYS functions ...
This should work on Linux (not sure what you mean with "sys functions", so it might be disallowed): ``` #include <sys/stat.h> mkdir("/tmp/foobar", 0); ```
This question already has answers here:what is the unsigned datatype?(7 answers)Closed6 years ago. I came across some C code which has 'unsigned' declaring a variable all by itself, like this: ``` unsigned crc = 0; ``` I think this is very strange because I'd expect an explicit variable type here. I'm surprised th...
From theC specification, section 6.7.2: — unsigned, or unsigned int Meaning thatunsigned, when not specified the type, shall default tounsigned int. So writingunsigned ais the same asunsigned int a.
Assuming I have the following function: ``` void process_data(uint32_t * data, size_t length) { for (size_t i = 0; i < length; i++) { foo(data[i]); } } ``` How can I tell Frama-C “this function ensures every access todata[i]satisfies conditioni < length”? As far as I understand, I can place an assert...
To prevent invalid memory accesses, you need to check that this function is always called with adatapointer from which at leastlengthelements can be read. So you need to write a precondition: ``` //@ requires \valid_read (data + (0 .. length-1)); void process_data(uint32_t * data, size_t length) { ``` So if you can ...
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.Closed6 years ago.Improve this question For my assignment, I've to write a function to create a directory but I'm not allowed to use SYS functions ...
This should work on Linux (not sure what you mean with "sys functions", so it might be disallowed): ``` #include <sys/stat.h> mkdir("/tmp/foobar", 0); ```
This question already has answers here:what is the unsigned datatype?(7 answers)Closed6 years ago. I came across some C code which has 'unsigned' declaring a variable all by itself, like this: ``` unsigned crc = 0; ``` I think this is very strange because I'd expect an explicit variable type here. I'm surprised th...
From theC specification, section 6.7.2: — unsigned, or unsigned int Meaning thatunsigned, when not specified the type, shall default tounsigned int. So writingunsigned ais the same asunsigned int a.
Assuming I have the following function: ``` void process_data(uint32_t * data, size_t length) { for (size_t i = 0; i < length; i++) { foo(data[i]); } } ``` How can I tell Frama-C “this function ensures every access todata[i]satisfies conditioni < length”? As far as I understand, I can place an assert...
To prevent invalid memory accesses, you need to check that this function is always called with adatapointer from which at leastlengthelements can be read. So you need to write a precondition: ``` //@ requires \valid_read (data + (0 .. length-1)); void process_data(uint32_t * data, size_t length) { ``` So if you can ...
This question already has answers here:what is the unsigned datatype?(7 answers)Closed6 years ago. I came across some C code which has 'unsigned' declaring a variable all by itself, like this: ``` unsigned crc = 0; ``` I think this is very strange because I'd expect an explicit variable type here. I'm surprised th...
From theC specification, section 6.7.2: — unsigned, or unsigned int Meaning thatunsigned, when not specified the type, shall default tounsigned int. So writingunsigned ais the same asunsigned int a.
Assuming I have the following function: ``` void process_data(uint32_t * data, size_t length) { for (size_t i = 0; i < length; i++) { foo(data[i]); } } ``` How can I tell Frama-C “this function ensures every access todata[i]satisfies conditioni < length”? As far as I understand, I can place an assert...
To prevent invalid memory accesses, you need to check that this function is always called with adatapointer from which at leastlengthelements can be read. So you need to write a precondition: ``` //@ requires \valid_read (data + (0 .. length-1)); void process_data(uint32_t * data, size_t length) { ``` So if you can ...
I doubt that the there is something wrong with the partition function. ``` void swap(int num1, int num2) { /*function to swap the values */ int temp = intArray[num1]; intArray[num1] = intArray[num2]; intArray[num2] = temp; } int partition(int left, int right) { //partition function int leftPointer = ...
Your partition algorithm always starts at element zero. It should start at the start of the partition.
I doubt that the there is something wrong with the partition function. ``` void swap(int num1, int num2) { /*function to swap the values */ int temp = intArray[num1]; intArray[num1] = intArray[num2]; intArray[num2] = temp; } int partition(int left, int right) { //partition function int leftPointer = ...
Your partition algorithm always starts at element zero. It should start at the start of the partition.
I seem to be having some issues with this 'for' loop, it is an exam question and I cannot figure out why my logic is incorrect. ``` int n = 1, r, i; for(i=0; i<5; i++) n *= 2; r = n--; ``` Find the value of r and n after this code has been run. Here is my logic for this(on paper, hence the image link):Image ...
The liner = n--;decrements n after it is assigned to r.
I'm writing a small app to manage iptables rules using libiptc. I have used some sample code fromhttps://it.bmc.uu.se/andlov/dev/library/Linux/libiptc/append.cto get started, but get the compiler error on line 31: error: ‘IPT_ALIGN’ was not declared in this scope size_t entry_size = IPT_ALIGN(sizeof(struct ...
It looks like the new macro may beCOMPAT_XT_ALIGN. The oldIPT_ALIGNwas just an alias ofXT_ALIGN, which appears to have been deprecated. (seehereandhere). I was not able to find any offical deprecation notice though.
In type flow_t, most members' value is zero. I want to check which members' value is not 0.I use commandx/1920xbto watch memory, but it's not convenient. ``` typedef struct flow { ... // There are more than 100 members. Total size is 1920 bytes. }flow_t; ```
There is no built-in way to do this in gdb. It can be done with a bit of scripting. There are, as usual, two basic approaches. The "old school" approach is to use a combination ofset loggingandshellto get the effect you want: print the result to a file, then grep for the interesting parts. The newer way would be t...
This question already has answers here:Dividing 1/n always returns 0.0 [duplicate](3 answers)Closed6 years ago. after compiling this code,I get k=0. shouldn't it be k=0.8? what's wrong with the code? ``` #include <stdio.h> #include <math.h> void main() { int x=8; int y=10; int m=6; float k; k=x/...
Although you are assigning the result of the division to afloat, the result itself is computed in integers. This is because both operands are of typeint. There are multiple ways of fixing this problem - for example, by assigning the dividend tok, and then dividing it by the divisor, like this: ``` int x=8; int y=10;...
I have auint8_ttypecast array of overall 36 bytes of data. I want to circularly shift thebitsthrough the entire array (right shift). How can I do this? eg.: ``` uint8_t arr[3] = {0x03, 0x44, 0x32} ``` after one shift it should be: ``` arr[3] = {0x01, 0xa2, 0x19} ```
Loop through each byte of the array. For each byte, first check the low bit and if it is set then set a carry-out flag. Then you can shift the byte right by one. Repeat the above for the next byte, but first set a carry-in flag to the current value of the carry-out flag. After shifting, check the carry-in flag and...
Can I change the memory of integer?Example: ``` int x;// Reservation 2 or 4 bytes in memory. ``` Is it possible to change 2 bytes to 40 bytes, for example?I am using C language.
You cannot change how many bytes the compiler allocates for an object when you use ``` int x; ``` If you want to allocate a certain number of bytes, use an array if the size is known at compile time. ``` char array[100]; ``` If the size is known only at run time, use dynamically allocated memory. ``` char* array ...
I am learning c, a beginner, can anybody please make me understood which concept am I missing? And thanks in advance. ``` #include<stdio.h> int main() { char s[10]; s[0]='A'; s[1]='B'; s[2]='\0'; char *p; int i; p=s; printf("%c\n", *p); //It's ok. printf("%s", *p); // or *s.....
Change ``` printf("%s", *p); ``` to ``` printf("%s", p); ``` The reason why is that%sis expecting a pointer, and*pis the dereferenced value atp, aka the char value atp[0]. If this doesn't make sense, picture whyprintf("%c\n", *p)works.*pis the same asp[0], which is the same ass[0]sinceppoints tos. Becauses[0]is a...
I wrote a program that it's duty is to read 20 numbers from user and put them in a list, after that it prints the value in array from bottom to starting point. But program stops exactly after reading second value from input. Source code : ``` #include <stdio.h> #define N 20 int main(void) { int numbers[N]; ...
If you want the loop to count downwards, then this loop ``` for(i=N;i<0;i--) ``` starts at the wrong index, and fails the test condition. It should be ``` for(i = N - 1; i >= 0; i--) ```
I have small problem with my C code. I want to read file until I hit certain character or EOF (from parameter as seen now).char *readUntil(FILE *stream, char character, size_t *length) I used this loop:int i = 0while((i = fgetc(stream)) != character || i != EOF){}to read it until stream ends or character is matched. ...
This line ``` while((i = fgetc(stream)) != character || i != EOF){} ``` will loop forever as either ``` i = fgetc(stream)) != character ``` or ``` i != EOF ``` will be true. Try ``` while((i = fgetc(stream)) != character && i != EOF){} ```
I'm an intermediate programmer of C++. I came across this code which prints number from 1-1000 without loop, not even recursion. And I've literally no idea how is this working. Can any please explain this code? ``` #include <stdio.h> #include <stdlib.h> void function(int j) { static void (*const ft[2])(int) = { ...
Just simple recursion: ``` static void (*const ft[2])(int) = { function, exit }; ``` First a function pointer array is created with fpointers tofunctionandexit, both taking anint. Thenft[j/1000](j + 1);calls the function at element[j/1000]which is0as long asjis less than 1000, sofunctionis called, otherwiseexitis c...
I wonder how to convert like a char: 1101_0110(D6) to two char(ascii format) 0100_0100(44) and 0011_0110(36). Thanks a lot!
sample code ``` #include <stdio.h> int main(void){ char x = '\xD6'; char asc[3]; sprintf(asc, "%02X", (unsigned char)x); printf("%s\n", asc);//D6 } ```
How the above declaration of function pointers work in C/C++. I first encountered this declaration while making use of the signal.h file in c programming.
This is a function pointer decalaration void (*var_name)(int) In this example,var_nameis a pointer to a function taking one argument,integer, and that returnsvoid. It's as if you're declaring a function called "*var_name", which takes an int and returns void; now, if *var_name is a function, then var_name must be a ...
I'm wondering why this code can work. I'm assuming that thescanfis assigning the value to the address of a pointer to achar. I know this expression is undefined but why doesprintfusing a pointer can print the correct value? ``` int main() { char* p; p = (char*)malloc(sizeof(char)); scanf("%c", &p); pr...
pis a variable that holds a memory address, and memory addresses are surely longer than 1 byte. If you store a char value in this variable, the previous value (the malloc'ed memory block) will be lost.printfjust treates your variable as acharvariable and prints its contents. If you suspected that the char would be sto...
I wonder how to convert like a char: 1101_0110(D6) to two char(ascii format) 0100_0100(44) and 0011_0110(36). Thanks a lot!
sample code ``` #include <stdio.h> int main(void){ char x = '\xD6'; char asc[3]; sprintf(asc, "%02X", (unsigned char)x); printf("%s\n", asc);//D6 } ```
How the above declaration of function pointers work in C/C++. I first encountered this declaration while making use of the signal.h file in c programming.
This is a function pointer decalaration void (*var_name)(int) In this example,var_nameis a pointer to a function taking one argument,integer, and that returnsvoid. It's as if you're declaring a function called "*var_name", which takes an int and returns void; now, if *var_name is a function, then var_name must be a ...
I'm wondering why this code can work. I'm assuming that thescanfis assigning the value to the address of a pointer to achar. I know this expression is undefined but why doesprintfusing a pointer can print the correct value? ``` int main() { char* p; p = (char*)malloc(sizeof(char)); scanf("%c", &p); pr...
pis a variable that holds a memory address, and memory addresses are surely longer than 1 byte. If you store a char value in this variable, the previous value (the malloc'ed memory block) will be lost.printfjust treates your variable as acharvariable and prints its contents. If you suspected that the char would be sto...
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed6 years ago. ``` #include<stdio.h> #define SQ(x) ((x)*(x)) main() { int i = 1; while( i<=5 ){ printf("result : %d\n", SQ(i++)); } } ``` execute window : result : 2 r...
SQ(i++) -> (i++)*(i++) Use this: ``` printf("result : %d\n", SQ(i)); i++; ```
I understand how_mm_shuffle_pswork. For example, in the following. ``` __m128 r = _mm_shuffle_ps(x,y, _MM_SHUFFLE(2,0,2,0)); ``` rwill have contents,x[0],x[2],y[0],y[2]. But I see that_MM_SHUFFLEalso takes 4 parameters for_mm256_shuffle_ps, while there the vectors would have 8 elements each. So, logically_MM_SHUFFL...
_mm256_shuffle_psshuffles each of the two 128-bits lanes independently, as if_mm_shuffle_psis called upon two XMM. If you want to shuffle all 8 32-bits elements, you need_mm256_permutevar8x32_ps
I have a C program that starts withint main()and somewhere in the code has ascanf(%d %c %d, &num1, &ch, &num2). Now I have another bash script that needs to test the C program. I want the bash script to run the C program and inject the arguments it received as input into the scanf (without making the C program stop a...
Create a text file with the input you want, space delimited. For example, for thescanf("%d %c %d", &num1, &ch, &num2);statement the contents oftestinput.txtwould be: ``` 42 x 99 ``` Save this file to the same directory as your program. Now run your program using input redirection ``` ./yourprogram < testinput.txt...
I keep getting error for my program and I would really appreciate it if someone can help. Here is the code: ``` #include <stdlib.h> #include <stdio.h> int main() { int x; float y; for ( x = 1; x < 21; x++) { y = (3(x * x) - x) / 18; printf("%d %10f\n", x, y); } return 0; } ...
3(x*x)should be3*(x*x)or just(3*x*x). The way you've written it, it looks like you are calling a function named3, which is not afunction or function pointer; hence the error message.
This is given: ``` signed short a, b; a = -16; b = 340; ``` Now I want to store these 2 signed shorts in one unsigned int and later retrieve these 2 signed shorts again. I tried this but the resulting shorts are not the same: ``` unsigned int c = a << 16 | b; signed short ar, br; ar = c >> 16; br = c & 0xFFFF; ```...
OP almost had it right ``` #include <assert.h> #include <limits.h> unsigned ab_to_c(signed short a, signed short b) { assert(SHRT_MAX == 32767); assert(UINT_MAX == 4294967295); // unsigned int c = a << 16 | b; fails as `b` get sign extended before the `|`. // *1u insures the shift of `a` is done as `unsigned...
I am working on a project that records the in time and out time Using C programming for attendance system. It was very difficult to write that data into EXCEL sheet format using C . So what I did was saved the data to a .csv file and saved it as a excel sheet. Does the newly saved file have the same properties as that...
Actualy if you open a CSV file with excel, it will Automatikly be Converted in excel Format. When you save this file, it will then keep this format.
When I run gdb, there seems to be a notion of a main file, as if I set a breakpoint with just a number, it will get set for the source file that contains themainfunction. How can I reconfiguregdbto set this to the file containing a function namedmy_main? (My actualmainis provided by my library, in 99.9% of cases I wa...
GDB isn't doing what you say. When you saybreak LINEit sets a breakpoint in the "current" file, as per the docs: The current source file is the last file whose source text was printed. So perhaps what you want is to always set a breakpoint inmy_main. If it helps you can make GDB let you up-arrow or Ctrl-R search b...
I understand how_mm_shuffle_pswork. For example, in the following. ``` __m128 r = _mm_shuffle_ps(x,y, _MM_SHUFFLE(2,0,2,0)); ``` rwill have contents,x[0],x[2],y[0],y[2]. But I see that_MM_SHUFFLEalso takes 4 parameters for_mm256_shuffle_ps, while there the vectors would have 8 elements each. So, logically_MM_SHUFFL...
_mm256_shuffle_psshuffles each of the two 128-bits lanes independently, as if_mm_shuffle_psis called upon two XMM. If you want to shuffle all 8 32-bits elements, you need_mm256_permutevar8x32_ps
I have a C program that starts withint main()and somewhere in the code has ascanf(%d %c %d, &num1, &ch, &num2). Now I have another bash script that needs to test the C program. I want the bash script to run the C program and inject the arguments it received as input into the scanf (without making the C program stop a...
Create a text file with the input you want, space delimited. For example, for thescanf("%d %c %d", &num1, &ch, &num2);statement the contents oftestinput.txtwould be: ``` 42 x 99 ``` Save this file to the same directory as your program. Now run your program using input redirection ``` ./yourprogram < testinput.txt...
I keep getting error for my program and I would really appreciate it if someone can help. Here is the code: ``` #include <stdlib.h> #include <stdio.h> int main() { int x; float y; for ( x = 1; x < 21; x++) { y = (3(x * x) - x) / 18; printf("%d %10f\n", x, y); } return 0; } ...
3(x*x)should be3*(x*x)or just(3*x*x). The way you've written it, it looks like you are calling a function named3, which is not afunction or function pointer; hence the error message.
This is given: ``` signed short a, b; a = -16; b = 340; ``` Now I want to store these 2 signed shorts in one unsigned int and later retrieve these 2 signed shorts again. I tried this but the resulting shorts are not the same: ``` unsigned int c = a << 16 | b; signed short ar, br; ar = c >> 16; br = c & 0xFFFF; ```...
OP almost had it right ``` #include <assert.h> #include <limits.h> unsigned ab_to_c(signed short a, signed short b) { assert(SHRT_MAX == 32767); assert(UINT_MAX == 4294967295); // unsigned int c = a << 16 | b; fails as `b` get sign extended before the `|`. // *1u insures the shift of `a` is done as `unsigned...
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.Closed6 years ago.Improve this question ``` int add(int a, int b) { return (int)&(((char *)a)[b]); } ``` Why am I supposed to castato achar *and...
The idea is that an array is simply an addition of a pointer with an index. Ifais achar [](orchar *) andbis an integer, thena[b]is the value at the addressa+b. This code is castingaas a pointer, indexing it with b, and finding the address, which should equala+b. But in the real world, don't ever ever ever do this.
I'm trying to create a multiplication program with beq, add, nand. This code works but I don't understand how this code exits the loop since the test value is always adding it self. Thank you for advice. (I'm using goto and label because I will make this code into mips assembly later). ``` unsigned mult(unsigned x, u...
testwill roll over and then the value will be 0. testwill take on the values1, 2, 4, 8, 16, 32, 64 ,.... 2147483648 , 0 The logic of the code is interesting, It checks if the LSbit ofxis 1. If yes, it addsyto the answer. If the next LSbit ofxit will add2*yto the answer. For each bit ofxthat is 1 it will add2^n*y,...
``` extern int test(); int main() { return test(); } ``` I build the code bygcc -c -o test.o test.c, and I find there is no name mangling when I runnm test.o.nmoutputstestbut not_test. My environment isubuntu 16.04gcc 5.4.0
You seem to be expecting global symbols to have an underscore prepended to them. This is something that isn't done in ELF which is the object format that linux uses. Older binary formats like a.out or coff required that, ELF doesn't. Btw. the term "mangling" is usually used for C++ symbol mangling which is a differen...
This question already has answers here:How can I convert an int to a string in C?(11 answers)Closed6 years ago. I would like to convert an integer to a string like: ``` int a = 12345 ``` coverts to ``` char b[6] = "12345" ``` basically the opposite of the atoi function that converts a string to an integer.
``` #include <stdio.h> int sprintf(char *str, const char *format, ...); ``` Example ``` char str[10]; sprintf(str,"%d", 12345); ```
When I type first value of linked list, console writes same value twice. For example, If I type a, it writes aa and then it goes normally. ``` if (r == NULL) { // If our list is empty... r = (node *) malloc(sizeof(node)); r->x = i; r->next = NULL; r->prev = NULL; iter = r; last = r; printf...
You are missing a bunch of useful code from your listing, but basically it will always print twice when creating the root node because bothifblocks will be executed. If you don't want them both executed, try usingelse iffor the second block.
``` struct Books { char title[50]; }; int main( ) { struct Books Book1; struct Books Book2; strcpy( Book1.title, "C Programming"); strcpy( Book2.title, "Telecom Billing"); printf( "Book 2 title : %s\n", Book2.title); printf( "Book 1 title : %s\n", Book1.title); } ``` Here, e...
BothBook1andBook2areautomaticvariables. They are automatically allocated once declared and automatically deallocated once they go out of scope. You must be very careful not to return any pointers to them once their function has returned. On most contemporary architectures they will reside on the stack (unless the com...
Is there any C/C++11 function like ``` whcar_t* source,destiantion; int location; copy(source,destination,location,partOfSource); ``` That copies partOfSource wchar-s from source to destination, starting from location in destination and location 0 in source, without terminating destination string with L'\0' ? Than...
There is a function for this in the C++ standard library. This works for any pointed type (char,wchar_t,int,whatever) and treats all values equally (no special treatment for a terminating value). This also works for all types of forward iterators, not just pointers. ``` std::copy(source, std::next(source, partOfSourc...
I have a header file that contains this function declaration: ``` bool isAbelianGroup(ConstGroupMemberP IdentityElement, ConstGroupMemberP members[], const int membersLen, const binaryOp oper, const freeMember freeMember, const GroupComparator compare); ``` I have a c file in which I ...
Found the problem: I should have writtenconst freeMember freeFuncin both h and c files instead ofconst freeMember freeMember. That was hard to find.
This question already has answers here:Divide contents of a unsigned char array into 2 halves(2 answers)Closed6 years ago. I am wondering if anyone can help me, I am only learning c and I am trying to split a BYTE array called c0[8] into 2 of size [4], then put each one of the size [4] into an unsigned int. By only u...
You could do it multiple ways, but bear in mind endianess (my examples are in little endian). Using memcpy: ``` memcpy(c0, &FirstHalf, sizeof(WORD32)); memcpy(&c0[sizeof(WORD32)], &SecondHalf, sizeof(WORD32)); ``` Simple assigment: ``` FirstHalf = (WORD32) c0[0] | (WORD32) c0[1] << 8 | (WORD32) c[2] << 16 | (WORD3...
I'm searching for a method to convert a two Byte UNICODEora variable (1-3 Byte) UTF-8 string to Chinese Simplified (GB2312). I found a lot of methods for php, Java, C# and Windows but nothing for standard "C". Right now, my best solution is to translate this JavaScript example:https://gist.github.com/19317362/a1d8e40...
As Remy Lebeau mentioned, I used the C-compatible library iconv.
I have the following multiple-choice question and I cannot figure out why (A) and (C) are incorrect, any explanation would be appreciated! The only correct answer in the following question is (B). Which of the following is a correct usage of scanf?(A)int i=0; scanf("%d", i);(B)int i=0; int *p=&i; scanf("%d", p);(C)ch...
scanfwants a correct address where to store the result: ``` (A) int i=0; scanf("%d", i); ``` iis passed here by value, no address: wrong. ``` (B) int i=0; int *p=&i; scanf("%d", p); ``` pis a pointer to int,scanfcan store its result here: right ``` (C) char *s="1234567"; scanf("%3s", &s); ``` &sis the address of...
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed6 years ago.Improve...
You need to add buffer size check at start of while loop if(i == sizeof(buffer)) break; and add \0 at the end of buffer if writeConfigParams expects a string
I have an assignment in University, where I need to write functions for a given main program. It is all in c. So, my problem is that I need to use the module of a sum of two unsigned integers. ``` uint32_t mod_add(uint32_t x, uint32_t y, uint32_t n) { uint32_t res; res = (x + y) % n; ``` This works fine, ...
Here you are. ``` uint32_t remainder(uint32_t x, uint32_t y, uint32_t d) { uint32_t r1 = x % d; uint32_t r2 = y % d; return r1 < (d - r2) ? r1 + r2 : r1 - (d - r2); } ``` Of course instead ofuint32_tyou can use any integer type as for exampleunsigned long long.
``` void test(void *a) { int *h = a; //error } int main(int argc, char const* argv[]) { int z = 13; test(&z); return 0; } ``` If I want to keep the void *a for test function, how can I get error line working?
I am able to compile and run the following withgccwithout warning or error: ``` #include <stdio.h> void test(void *a) { int *h = a; printf("test: %d\n", *h); } int main(int argc, char const* argv[]) { int z = 13; test(&z); return 0; } ``` The only conceivable reason you woul...