question
stringlengths
25
894
answer
stringlengths
4
863
The following code access to memory that is no more allocated. ``` #include <stdio.h> int main() { int * ptr = new int(5); delete ptr; return *ptr; } ``` The pointer access to memory that is no more allocated but till the memory is accessible it will just return a value. I wonder if, practica...
I wonder if it is possible that this makes crash the program with a segmentation violation signal or such kind of thing. Yes. De-referencing a deleted pointer isundefined behaviour. One of the things could happen is a crash. Another is that the program could silently exit without any problems.
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.Closed9 years ago.Improve this question Example Say that I have an array: ``` Array = (9, 1, 9, 9); ``` how can I loop through the array and pri...
The simplest way I can think of is to go over the array once and find the max value, then go over the array again and print the message with the current index each time you get to an element which is equal to the max you have found.
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed9 years ago.Improve this question If I can do a cycle with for and while both, which should I choose? [for] ``` int ...
The choice betweenforandwhileis just matter of clarity: K&R . Chapter 1. The For statment: The choice between while and for is arbitrary, based on which seems clearer. The for is usually appropriate for loops in which the initialization and increment are single statements and logically related, since it ...
``` #include<stdio.h> void main() { float a=10.5; printf("%d%d",sizeof(a),sizeof(10.5)); } ``` OUTPUT: 4 8 I want to know why it happens?
In C a floating point literal is actually a double unless you suffix it with an f (i.e.10.5f).
This question already has answers here:Why is a condition like (0 < a < 5) always true?(4 answers)Closed9 years ago. I have this question & in the answer it says that due to left to right associativity the result would be 1 that is true for this statement. This is the code. ``` #include<stdio.h> int main () { int i...
The expression x ``` (x < y) < z ``` so it becomes ``` (10 < 10) < 5 ``` which further is evaluated into ``` 0 < 5 ``` which is true. I think you wanted something like this: ``` x < y && y < z ```
This question already has answers here:How can I access a shadowed global variable in C?(6 answers)Closed9 years ago. ``` #include <stdio.h> /* global variable declaration */ int g = 20; int main () { /* local variable declaration */ int g = 10; printf ("value of g = %d %d\n", g,::g); return 0; } ``` W...
No, that's a C++ feature. In C, declaring a variable in an inner scope will hide the one in the outer scope. If youmustdo it, you can use pointers to get at the outer scope but it's a bit of a kludge and not something I'd recommend: ``` #include <stdio.h> int g = 20; int main () { int *pGlobalG = &g; int g = 10;...
I am wondering why is it that regardless if I input a digit or a letter or a character it keeps printing the last print line, how come the yes "This is an integer line never work? How do I go about getting the user to only input a positive digit? ``` #include <stdio.h> #include <limits.h> main(){ unsigned int ...
changeelse if ( num >= '0' && num <= '9')toelse if ( num >= 0 && num <= 9), assume you input a number between 0 and 9.
I've been searchingStack Overflowfor a guideline on the max amount of memory one should allocate on the stack. I see best practices for stack vs. heap allocation but nothing has numbers on a guideline on how much should be allocated on the stack and how much should be allocated on the heap. Any ideas/numbers I can u...
In a typical case, the stack is limited to around 1-4 megabytes. To leave space for other parts of the code, you typically want to limit a single stack frame to no more than a few tens of kilobytes or so if possible. When/if recursion gets (or might get) involved, you typically want to limit it quite a bit more than t...
After running this code: ``` #include <stdio.h> int x; int main(void) { printf("%d\n",x); return 0; } int x=5; ``` I expected the output should be0. Because of thesequence control structureof the programint x;should be executed first and then0is printed and finallyint x=5;should be executed. But it is givin...
The first acts as a forward declaration, and the later acts as the actual definition.
Say there is a very large number, 100 digits which is stored in an array. Now i want to divide this number by another number(say 2) , Can anyone suggest how to do it?
Try to do it exactly as you would do that on paper. For small divisors (as 2) this is an O(d) algorithm (where d is the number of digits) and it is impossible to find anything asymptotically better since you need to check each digit at least once.
Example Tree ``` 2 -> root 1 -> Left 3 -> right ``` stored in array in in order [1, 2, 3] How to retrieve the root node knowing that the tree is stored in inorder? According to me all three as possible candidates of root node.
Indeed all 3 are possible candidates. Here are possible trees that would result in the given in-order traversal: ``` 1 2 3 \ / \ / 2 1 3 2 \ / 3 1 ``` An in-order traversal isn't necessarily sufficient to uniquely identify...
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.Closed9 years ago.Improve this question I'm reading a book about C, and GNU but it references code on a 32 bit processor. I've already figured out ...
Your code should be ``` pointr = &j; ``` Withpointr = j;you are assigning value ofji.e10to the pointer.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question So i have a question about pthreads. The thing is i have 3 pites of threads lets call th...
priority and mutex are independent concepts. For you case, you can set the priority of T2 to be higher than T3. refer topthread_setschedparam
Here's Exercise 5-11: Modify the program entab and detab (written as exercises in Chapter 1) to accept a list of tab stops as arguments. Use the default tab settings if there are no arguments. entab is described as Replace strings of blanks by minimum # of tabs/blanks to achieve same spacing. A tab should be given p...
When you hittab, you travel to the next tab stop. For example, many text editors have the tab stops at all multiples of 8 (8, 16, 24, 32, 40, etc) so if you are in column (say) 11 and hit tab you go to column 16. If you're in column 14 and hit tab you also go to column 16. So a tab is not always worth a fixed amoun...
Well, I'm trying to do a simple script to check any updates in an application. To check this, the most simple way I found is to connect to the FTP (where have a file which says the last update) and compares X file with a Y file. If the Y file is outdated, the script should run an installer/updater. Can I do it with C?...
Well, I found another way to do this with a Batch File. I'm connecting to the FTP using the script (ftp -s:commands.txt ip.ftp) and then I use a comparation to check the differences. The rest was simple. Thank you all.
I have a stat struct and I want to create a folder or a file and want to force it to have the same information as in the stat struct. For instance: ``` create file: test.txt The file's last modification date is today 16.01.2014 change file's stat so that it shows: last modified on 01.01.2050 ``` How can I do that?
If you want to set themtime/atimefields, you can use theutime()function. Use it after creating the file/directory. Themodefield is set withchmod() Theuid/gid, if you are root, are set withchown(). The fieldssizeandnlinkswill have the correct value if you set the information they refer to (the data of the file and t...
This question already has answers here:C non-blocking keyboard input(11 answers)Closed9 years ago. Let's suppose I'm in awhile (1)loop calculating something, would it be possible to quit the whole application by pressing a certain key? It's a C console application without threads. I'm pretty sure it's not possible,...
On Windows systems, there'skbhit()function that is nonblocking and returnstruewhen any key is pressed. So, you could changewhile(1)towhile(!kbhit()), or you couldif(kbhit()) c = getch()to read the char without waiting. But this is very crude solution, really..
``` void main() { struct bitfield { unsigned a:5; unsigned c:5; unsigned b:6; }bit; char *p; struct bitfield *ptr,bit1={1,3,3}; p=&bit1; p++; printf("%d",*p); } Explanation: ``` Binary value of a=1 is 00001 (in 5 bit)Binary value of b=3 is 00011 (in 5 bit)Bin...
The actual representation is like: ``` 000011 00011 00001 b c a ``` When aligned as bytes: ``` 00001100 01100001 | | p+1 p ``` On the address (p+1) is0001100which gives 12.
Is there anyway in C to get an image, stream by stream and how can I understand how many stream there are in an Image? the Image is in JPEEG type. and for saving this stream in another file I'll have any problem?
You can have a look to the free OpenCV library :http://opencv.org/ Here there is a tutorial with some examples :http://www.cs.iit.edu/~agam/cs512/lect-notes/opencv-intro/ It's largely used for this kind of treatments.
I think question is clear enough - Is there any "man" like command to list structure members? For example "FILE" structure, I want to know the member of FILE that contains file descriptor ID.
FILEis opaque. The members are none of your business unless you're hacking the C library. Thefilenofunction returns the file descriptor for a givenFILE *. For structures that aren't meant to be opaque, you normally find the members you're allowed to access listed in the man page for the function that returns the str...
I have a C program running on a Unix box. I would like to print a timestamp to an output file - at the moment I use the commanddateto print the datetime on the terminal. ``` fprintf(outputfile, "%s ", date); ``` How do I go about doing this?
Use POSIXstrftime(3) - format date and timefor a C solution. It use the same format strings asdate(1) I also recommend you read thestandard library intro(3).
This question already has answers here:Why does the compiler allow initializing a variable with itself? [duplicate](2 answers)Closed9 years ago. I am a bit baffled that I managed to accidentally write code equivalent to this one ``` int a=a; // there is not a declared before this line ``` and the compiler happily c...
It will be a compile-time error if you tell GCC to make it so: ``` gcc -Winit-self -Werror ``` Note that sadly this diagnostic is not enabled by most of the usual suspects like -Wall.
I need to update file timestamps (namelyst_ctime,st_atime,st_mtime) of an existing file in a C program. On Win32, I could useSetFileTimeto update the timestamps. How do I achieve the same on Linux? EditI knowtouchbut since I've put aCtag to the question, I hoped that I could do it with a system call instead of ca...
I'm not sure you can change the creation time of a file but you can use theutimefunction to change the access and modified times.
I started trying to integrate some C libraries into my Go code for a project using cgo and have come across a problem. In one of the C functions I need to pass argv to a function call. In C argv is a pointer to an array of char strings (K&R C, §5.10) and I need to convert from a slice of strings to a char**. I have ...
You'll need to create the array yourself. Something like this should do: ``` argv := make([]*C.char, len(args)) for i, s := range args { cs := C.CString(s) defer C.free(unsafe.Pointer(cs)) argv[i] = cs } C.foo(&argv[0]) ```
I have mp4 video which has around 50000 frames of size 1920x720. I have to remove a specific area in the video (all frames). Can you suggest a method in MATLAB?
Specify a ROI(Region of Interest) for each individual frame of the video, where the ROI is the specific area that you wanted to remove. Quite simple. Hope my advice helped. If u are still not sure, comment on this answer, I will add in more hints.
I am trying to assign a string or an int to msg to send it later to a server. This code is in the client. ``` char msg[100]; int a; . . . bzero (msg, 100); printf ("[client]your message: "); fflush (stdout); read (0, msg, 100); /* sending message to server */ if (w...
``` sprintf(msg, "%d\n", a); ... write(sd, msg, strlen(msg)); ``` This assumes the client is expecting a string of digits (representing an integer) followed by a newline. I arbitrarly chose a newline delimiter, but you must havesomeconvention by which the server knows what the heck you're sending.
I would like to be able to print the stack trace of a thread in the Linux kernel. In details: I want to add code to specific functions (e.g.swap_writepage()) that will print the complete stack trace of the thread where this function is being called. Something like this: ``` int swap_writepage(struct page *page, stru...
Linux kernel has very well known function calleddump_stack()here, which prints the content of the stack. Place it in your function according to see stack info.
I have mp4 video which has around 50000 frames of size 1920x720. I have to remove a specific area in the video (all frames). Can you suggest a method in MATLAB?
Specify a ROI(Region of Interest) for each individual frame of the video, where the ROI is the specific area that you wanted to remove. Quite simple. Hope my advice helped. If u are still not sure, comment on this answer, I will add in more hints.
I am trying to assign a string or an int to msg to send it later to a server. This code is in the client. ``` char msg[100]; int a; . . . bzero (msg, 100); printf ("[client]your message: "); fflush (stdout); read (0, msg, 100); /* sending message to server */ if (w...
``` sprintf(msg, "%d\n", a); ... write(sd, msg, strlen(msg)); ``` This assumes the client is expecting a string of digits (representing an integer) followed by a newline. I arbitrarly chose a newline delimiter, but you must havesomeconvention by which the server knows what the heck you're sending.
I would like to be able to print the stack trace of a thread in the Linux kernel. In details: I want to add code to specific functions (e.g.swap_writepage()) that will print the complete stack trace of the thread where this function is being called. Something like this: ``` int swap_writepage(struct page *page, stru...
Linux kernel has very well known function calleddump_stack()here, which prints the content of the stack. Place it in your function according to see stack info.
I have mp4 video which has around 50000 frames of size 1920x720. I have to remove a specific area in the video (all frames). Can you suggest a method in MATLAB?
Specify a ROI(Region of Interest) for each individual frame of the video, where the ROI is the specific area that you wanted to remove. Quite simple. Hope my advice helped. If u are still not sure, comment on this answer, I will add in more hints.
I am trying to assign a string or an int to msg to send it later to a server. This code is in the client. ``` char msg[100]; int a; . . . bzero (msg, 100); printf ("[client]your message: "); fflush (stdout); read (0, msg, 100); /* sending message to server */ if (w...
``` sprintf(msg, "%d\n", a); ... write(sd, msg, strlen(msg)); ``` This assumes the client is expecting a string of digits (representing an integer) followed by a newline. I arbitrarly chose a newline delimiter, but you must havesomeconvention by which the server knows what the heck you're sending.
I would like to be able to print the stack trace of a thread in the Linux kernel. In details: I want to add code to specific functions (e.g.swap_writepage()) that will print the complete stack trace of the thread where this function is being called. Something like this: ``` int swap_writepage(struct page *page, stru...
Linux kernel has very well known function calleddump_stack()here, which prints the content of the stack. Place it in your function according to see stack info.
I have a shared memory X (array), 2 type of process and I have 3 semaphores, one for modifier X and the other one is for wait until I want to wake up one of these waited process. Step by step: ``` 1. I'm the process 1 and I ask for semaphore 1 (mutex). 2. OK I got it so I can add me in the array, now I wait (semapho...
You might use thekill(2)syscall to send a signal to some given process. I am not sure it is the best way to synchronize (I believe it is not; readsignal(7)). You could use Posix semaphoressem_overview(7)(or even old SysV semaphoressvipc(7)) or pipespipe(7)(orunix(7)sockets) withpoll(2) ReadAdvanced Linux Programmin...
Would like to know why cannot I declare a Static variable inforloop initialization as shown below, ``` for(static int i = 0;;) ``` Compiling the above loop statement code with myC99standard compiler I see the below error, ``` error: declaration of static variable ‘i’ in ‘for’ loop initial declaration ```
C does not allow it C11dr 6.8.5Iteration statements3 "The declaration part of aforstatement shall only declare identifiers for objects having storage classautoorregister". (notstatic) Typically code would not benefit form being able to have an iterator that isstatic. storage-class-specifier: ``` typedef exte...
Infopen("myfile", "r+")what is the difference between the"r+"and"w+"open mode? I read this: "r"Open a text file for reading."w"Open a text file for writing, truncating an an existing file to zero length, or creating the file if it does not exist."r+"Open a text file for update (that is, for both reading and writi...
Bothr+andw+can read and write to a file. However,r+doesn't delete the content of the file and doesn't create a new file if such file doesn't exist, whereasw+deletes the content of the file and creates it if it doesn't exist.
This question already has an answer here:CUDA function call-able by either the device or host(1 answer)Closed9 years ago. In order to call the same function from host code and GPU kernel, Do I have to keep the two copies of the same function as below: ``` int sum(int a, int b){ return a+b; } __device int sumGPU(int...
You just have to add the__host__keyword to be able to call call a function from host or device. ``` __host__ __device__ int sum(int a, int b){ return a+b; } ```
I'm using the blackfin toolchain with gcc for a project I'm working on. I have to switch the toolchain for different applications on different platforms. The name of this toolchain is defined with the --with-pkgversion flag. I want to generate a compile error when the application is being build with the incorrect tool...
Rungcc -E -dM src.c.This will give you a list of all macros defined. If what you want exists, it will be there.
Would like to know why cannot I declare a Static variable inforloop initialization as shown below, ``` for(static int i = 0;;) ``` Compiling the above loop statement code with myC99standard compiler I see the below error, ``` error: declaration of static variable ‘i’ in ‘for’ loop initial declaration ```
C does not allow it C11dr 6.8.5Iteration statements3 "The declaration part of aforstatement shall only declare identifiers for objects having storage classautoorregister". (notstatic) Typically code would not benefit form being able to have an iterator that isstatic. storage-class-specifier: ``` typedef exte...
Infopen("myfile", "r+")what is the difference between the"r+"and"w+"open mode? I read this: "r"Open a text file for reading."w"Open a text file for writing, truncating an an existing file to zero length, or creating the file if it does not exist."r+"Open a text file for update (that is, for both reading and writi...
Bothr+andw+can read and write to a file. However,r+doesn't delete the content of the file and doesn't create a new file if such file doesn't exist, whereasw+deletes the content of the file and creates it if it doesn't exist.
This question already has an answer here:CUDA function call-able by either the device or host(1 answer)Closed9 years ago. In order to call the same function from host code and GPU kernel, Do I have to keep the two copies of the same function as below: ``` int sum(int a, int b){ return a+b; } __device int sumGPU(int...
You just have to add the__host__keyword to be able to call call a function from host or device. ``` __host__ __device__ int sum(int a, int b){ return a+b; } ```
I'm using the blackfin toolchain with gcc for a project I'm working on. I have to switch the toolchain for different applications on different platforms. The name of this toolchain is defined with the --with-pkgversion flag. I want to generate a compile error when the application is being build with the incorrect tool...
Rungcc -E -dM src.c.This will give you a list of all macros defined. If what you want exists, it will be there.
Infopen("myfile", "r+")what is the difference between the"r+"and"w+"open mode? I read this: "r"Open a text file for reading."w"Open a text file for writing, truncating an an existing file to zero length, or creating the file if it does not exist."r+"Open a text file for update (that is, for both reading and writi...
Bothr+andw+can read and write to a file. However,r+doesn't delete the content of the file and doesn't create a new file if such file doesn't exist, whereasw+deletes the content of the file and creates it if it doesn't exist.
This question already has an answer here:CUDA function call-able by either the device or host(1 answer)Closed9 years ago. In order to call the same function from host code and GPU kernel, Do I have to keep the two copies of the same function as below: ``` int sum(int a, int b){ return a+b; } __device int sumGPU(int...
You just have to add the__host__keyword to be able to call call a function from host or device. ``` __host__ __device__ int sum(int a, int b){ return a+b; } ```
I'm using the blackfin toolchain with gcc for a project I'm working on. I have to switch the toolchain for different applications on different platforms. The name of this toolchain is defined with the --with-pkgversion flag. I want to generate a compile error when the application is being build with the incorrect tool...
Rungcc -E -dM src.c.This will give you a list of all macros defined. If what you want exists, it will be there.
Doxygen seems to expect C++ and lists my structs as "classes" in the HTML output. How can I get Doxygen to process my source as C not C++?
Try ``` OPTIMIZE_OUTPUT_FOR_C=YES ``` in yourDoxyfile, see if that's more to liking.
I have entered the following code inturbo c++. ``` #include<graphics.h> #include<conio.h> int main() { int gd= DETECT, gm; initgraph(&gd,&gm,"D:\\TC\\BGI"); getch(); closegraph(); return 0; } ``` It compiles without any errors and warning. But when I run the program the following ...
If you are using Turbo C .. just need to check one option: Go toOptions->Linker->Librariesand check the Graphics Library option
How to ``` if (x == 1) printf("2\n"); else if (x == 2) printf("1\n"); else printf("0\n"); ``` using bitwise operators? My attempt is: ``` for (x = 0; x < 8; x++) { printf("%d\n", 0x03 & (0x03 ^ x)); } ``` Output: ``` 3 2 1 0 3 2 1 0 ``` Desired output: ``` 0 2 1 0 0 0 0 0 ```
This is insane, but I finally figured it out: ``` printf("%d\n", (3 & ~(x & 3)) & (0xfc >> (x << 1))); ```
i'm creating an automation framework in python for our android devices. i've written a wrapper for adb commands by using Popen to run adb. this is nice but i'de rather skip on the process creating for every call (many calls to adb) So i thought about creating bindings for the C code (adb is in C). As far as i underst...
No need forcbindings. Just use sockets to connect to theadbdaemon from your python codehttps://gist.github.com/ktnr74/6755712
I am asking how can I read a double, int or any other type fromstdinusing thereadsystem call. What I've done so far: ``` long val ; ssize_t r; r = read(STDIN_FILENO,&val,sizeof(long)); printf("%ld\n",val); ``` Any idea?
You are not being clear whether you want to read (a) the ASCII representation of a long, double, int or whatever (i.e. the string "0.12345", or (b) the binary representation of that value. If you want to do (a), you need to usefscanf. See the above answer. If you want to do (b), your code looks right to me. What is ...
So, the correct way of calculatingmidin a binary search ismid = low + ((high - low) / 2)in order to handle overflow errors. My implementation uses unsigned 64 bit variables and I don't ever see a situation where my arrays get so big so as to cause an overflow. Do I still need use the above implementation or can I use...
If there is no possibility of overflow, the overflow-safe way of computing the midpoint is technically unnecessary: you can use the unsafe formula if you wish. However, it's probably a good idea to keep it there anyway, in case that your program gets modified some day to break your assumptions. I think that adding a s...
I work in simulation software and one of the many operations done on arrays is scaling a vector by a number. I have code like this: ``` //Just some initialization code, don't bother about this part int n = 10000; std::vector<double> input(n, 42.0); std::vector<double> output(input.size()); double alpha = 69.0; //t...
The solution I came up with was callingcblas_dcopy()thencblas_dscal(). It is not the best of all worlds but it is still faster than the raw loop.
I have an 8 bits variable and I need to detect if that variable contains another value different of 'S' or 'G'. I try the following code ``` if(XType!='S' || XType!='G') { Reload(); } ``` As I realize now, that didn't work. :( I'm not allowed to use any library it must be resolved logically cause is very basi...
``` if(XType!='S' || XType!='G') ``` will always evaluate true. (ifXTypeis'G'thenXType!='S'will be true; anything else will mean thatXType!='G'will be true. Logical OR||will evaluate true if at least one of its inputs is true so your condition will always be true.) Try using logical AND&&instead. This only evalua...
Thebind()function accepts a pointer to asockaddr, but in all examples I've seen, asockaddr_instructure is used instead, and is cast tosockaddr: ``` struct sockaddr_in name; ...; if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) { ...; } ``` I can't wrap my head around why is asockaddr_instruct used. W...
No, it's not just convention. sockaddris a generic descriptor for any kind of socket operation, whereassockaddr_inis a struct specific to IP-based communication (IIRC, "in" stands for "InterNet"). As far as I know, this is a kind of "polymorphism" : thebind()function pretends to take astruct sockaddr *, but in fact, ...
I have seen code where people will use const as a parameter to the function. What are the benefits of using const* vs const * const? This might be a very basic question but I would appreciate if someone could explain. ``` Bool IsThisNumberEqualToFive(int const * num) { return(Bool)(5 != num ); } Bool IsThisNumbe...
In the first version you promise you're not going to write to the object thatnumpoints toIn the second version you promise that and you also prevent yourself (i.e. IsThisNumber..) from makingnumpoint to something else. That is, in the second versionthe pointer itself is alsoconst, in addition to the pointee.
So, that's the question: can I increment theivariable insideforloop?: ``` for(int i = 0; i < 1000; i++) { i++; // is this legal? if not what is the alternative? } ```
Absolutely legal but not very intuitive. Consider using a while loop instead if you need to manipulate your looping in this way (it's just a code clarity thing, not a legal thing).
I was looking into using Apple's Blocks runtime with clang on Linux, and I uncovered theincompatibility issueswith the GNU libc's<unistd.h>. Looking around a bit for more information I found one usersuggesting: Oh well time to use a different libc? I hear FreeBSD has a nice one! :-) As seemingly implied, this is a...
I can think of three reasons off the top of my head. Legacy Reasons: You have code written against the oldRogue Wave,Size: There'smuslanddietlibc,ToPerform Android Cross CompileusingBionic
This question already has an answer here:What does "void *(*)(void *)" mean in C++?(1 answer)Closed9 years ago. I came across a function call ``` // call the entry point from the ELF header // note: does not return! ((void (*)(void)) (ELFHDR->e_entry & 0xFFFFFF))(); ``` ELFHDR->e_entry is a function pointer...
``` void (*)(void) ``` is the type pointer to a function with no parameter and that returns no value. For example: ``` void foo(void) { } void (*p)(void) = foo; // p is of type void (*)(void) ```
I understand a condition is supposed to be for example y==3, but y-3 is totally confusing to me. I can't understand this code. If y-3 is true it prints 1. How can y-3 be true or false?
The expressiony - 3results in a value which can be tested for truthness. In C 0 is false and any non-zero value is true. Sayingif (y - 3)is essentially sayingif (y - 3 != 0)or even more succinctlyif (y != 3)
The C standard mandatessizeof(char)to be1, no matter how many bits it actually takes.Are other data-types measured in terms ofbytesorcharsin case these are not the same? Basically, assumingCHAR_BITis16, wouldsizeof(int16_t)be equal to1or2?
Basically, assuming CHAR_BIT is 16, would sizeof(int16_t) be equal to 1 or 2 Size of objects (as yielded bysizeofoperator) is measured in bytes and abytein C hasCHAR_BITbits. (C99, 6.2.6.1p4) "Values stored in non-bit-field objects of any other object type consist of n x CHAR_BIT bits, where n is the size of an obje...
This question already has answers here:warning: return type defaults to ‘int’ [-Wreturn-type](4 answers)Closed8 years ago. ``` #include <stdio.h> int w=7,v=0; shortf(short a, short *b) { a++;(*b)++;w++;v++; printf("13: %d %d %d",a,v,w); return a; } int main() { return 0; } ``` This is part of my code. It...
You did not declare a return type for the functionshortf. And so the compiler warned you that the default type ofintwill be used. You should always declare a return value type. My guess is that the code has just been transcribed incorrectly. I think it should be: ``` short f(short a, short *b) ```
As the title says, how would you go about converting a standard GTK3 application written in C (although Python should work as well with thegobjectbindings) to have client-side decorations? I really like the idea, but I couldn't find anything that did this other than the default Gnome 3.10 apps (settings, tweak tool et...
GTK+ windows by default are decorated by the window manager. You can request the titlebar of an application be replaced in GTK+ 3.10 or higher by calling ``` gtk_window_set_titlebar(window, header); ``` whereheaderis aGtkHeaderBarwidget andwindowis the window you wish to have client side decorations. The official GN...
The code below returns a warning message, I can't understand why and also couldn't find an answer among questions about the same warning message. I'll thank to get the right code and the explanation about the warning message. The warning is: WARNING: assignment from incompatible pointer type The code is: ``` #incl...
the function declaration should be (you omitted the parameter type): ``` mytype sum(mytype sum_operation) { ```
I'm new to arrays , i want to know if it is possible to fill the array using a for-loop with the scanf function , i made a first attempt but the program isn't working ( it is supposed to fill the array then print all the elements of it ) ``` #include<stdio.h> void main(){ int n,i; int table[10]; for(...
When you declare an array of size N, the elements are indexed from 0 to N - 1. From there, you need to pass theaddressof your variable toscanf, not the variable itself. Since you are using an array, this becomes very simple. ``` for (int i = 0; i < 10; ++i) scanf("%d", table + i); ```
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.Closed9 years ago.Improve this question I'd love to create some part dynamically. Would it be possible to useoffsetofwith string as a second argume...
Theoffsetofconstruct is a compile time operation. It can't be used with anything that is generated dynamically.
This question already has answers here:Division without using '/'(16 answers)Closed5 years ago. How can I divide a number with an unknown number without using these operators('*', '/', '%'). Denominator is given during runtime.
``` void main(){ int a,b,i=0; clrscr(); printf("Enter the dividend and divisor"); scanf("%d%d",&a,&b); while(a>=b){ a=a-b; i++; } printf("qoutient is :%d \n remainder : %d",i,a); getch(); } ```
received_datais aglobalchar arrayof length 256. It contains a string at offsetrx_pos_pi.e.received_data[rx_pos_p]. I want to return the address of this string through a pointermem, but I think I am making a mistake. I have written the function as follows: ``` uint8_t get_bytes(char **mem, uint8_t len){// Be watchful ...
You need to do : ``` *mem = &received_data[rx_pos_p]; ``` You want to return the pointer in the pointerpointer, so you must dereference it.
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.Closed9 years ago.Improve...
Compilation happens from top to bottom. so value of a is replaced by 50 when it enters into main function. Here the local has precedence than global
I am implementing a multi-threaded program in which I am waiting formyThreadto reurn a value. I am doing it as follows: ``` result = pthread_join(myThread, &retValue); ``` wheremyThreadreturns a(void *)returnValue. My program gives aSegmentation Faultwhen I try to print the return value using: ``` printf("Returned ...
You've confused the return type. At the end of your thread you cast from a(long)to a(void *). ``` return (void *) count ; ``` Back in main, you are casting(void *)to a(long *)and then trying to dereference it. Since count is probably a small number, treating that as a memory address goes boom. Treat it as a(long)...
I'm new to arrays , i want to know if it is possible to fill the array using a for-loop with the scanf function , i made a first attempt but the program isn't working ( it is supposed to fill the array then print all the elements of it ) ``` #include<stdio.h> void main(){ int n,i; int table[10]; for(...
When you declare an array of size N, the elements are indexed from 0 to N - 1. From there, you need to pass theaddressof your variable toscanf, not the variable itself. Since you are using an array, this becomes very simple. ``` for (int i = 0; i < 10; ++i) scanf("%d", table + i); ```
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.Closed9 years ago.Improve this question I'd love to create some part dynamically. Would it be possible to useoffsetofwith string as a second argume...
Theoffsetofconstruct is a compile time operation. It can't be used with anything that is generated dynamically.
This question already has answers here:Division without using '/'(16 answers)Closed5 years ago. How can I divide a number with an unknown number without using these operators('*', '/', '%'). Denominator is given during runtime.
``` void main(){ int a,b,i=0; clrscr(); printf("Enter the dividend and divisor"); scanf("%d%d",&a,&b); while(a>=b){ a=a-b; i++; } printf("qoutient is :%d \n remainder : %d",i,a); getch(); } ```
received_datais aglobalchar arrayof length 256. It contains a string at offsetrx_pos_pi.e.received_data[rx_pos_p]. I want to return the address of this string through a pointermem, but I think I am making a mistake. I have written the function as follows: ``` uint8_t get_bytes(char **mem, uint8_t len){// Be watchful ...
You need to do : ``` *mem = &received_data[rx_pos_p]; ``` You want to return the pointer in the pointerpointer, so you must dereference it.
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.Closed9 years ago.Improve...
Compilation happens from top to bottom. so value of a is replaced by 50 when it enters into main function. Here the local has precedence than global
I am implementing a multi-threaded program in which I am waiting formyThreadto reurn a value. I am doing it as follows: ``` result = pthread_join(myThread, &retValue); ``` wheremyThreadreturns a(void *)returnValue. My program gives aSegmentation Faultwhen I try to print the return value using: ``` printf("Returned ...
You've confused the return type. At the end of your thread you cast from a(long)to a(void *). ``` return (void *) count ; ``` Back in main, you are casting(void *)to a(long *)and then trying to dereference it. Since count is probably a small number, treating that as a memory address goes boom. Treat it as a(long)...
This question already has answers here:Division without using '/'(16 answers)Closed5 years ago. How can I divide a number with an unknown number without using these operators('*', '/', '%'). Denominator is given during runtime.
``` void main(){ int a,b,i=0; clrscr(); printf("Enter the dividend and divisor"); scanf("%d%d",&a,&b); while(a>=b){ a=a-b; i++; } printf("qoutient is :%d \n remainder : %d",i,a); getch(); } ```
received_datais aglobalchar arrayof length 256. It contains a string at offsetrx_pos_pi.e.received_data[rx_pos_p]. I want to return the address of this string through a pointermem, but I think I am making a mistake. I have written the function as follows: ``` uint8_t get_bytes(char **mem, uint8_t len){// Be watchful ...
You need to do : ``` *mem = &received_data[rx_pos_p]; ``` You want to return the pointer in the pointerpointer, so you must dereference it.
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.Closed9 years ago.Improve...
Compilation happens from top to bottom. so value of a is replaced by 50 when it enters into main function. Here the local has precedence than global
I am implementing a multi-threaded program in which I am waiting formyThreadto reurn a value. I am doing it as follows: ``` result = pthread_join(myThread, &retValue); ``` wheremyThreadreturns a(void *)returnValue. My program gives aSegmentation Faultwhen I try to print the return value using: ``` printf("Returned ...
You've confused the return type. At the end of your thread you cast from a(long)to a(void *). ``` return (void *) count ; ``` Back in main, you are casting(void *)to a(long *)and then trying to dereference it. Since count is probably a small number, treating that as a memory address goes boom. Treat it as a(long)...
I downloaded a .tgz file which contains R scripts in R/ and a single C file in src/. An R function calls the C function in this way: ``` Mainfn<-function(x) { output <- matrix(nrow(x),ncol(x)); output<-.C("myCfn",x=as.double(x),output=as.double(output), PACKAGE='mypackage') return(output) } ``` I...
My best guess: the package needsuseDynLib(<pkg_name>)in itsNAMESPACEfile.
I'm writing this code to use sizeof() function with a char array of 7 elements, I thought that the output should be 8 because of the 7 elements PLUS the terminator of the array but surprised that the output was 5?? HOW COME? ``` #include<stdio.h> int main(void) { char str[]="S\065AB"; printf("\n%d",sizeof(st...
\065is a single character, represented as an octal escape sequence.
I'm curios especially about word "completion" Example in C or Objective-C?
in short: the idea of a completion function is: do something and tell me once you did it e.g. from UIKit pushViewController:animated:completionHandler:oranimate:completion: the idea of callbacks I : Do something and tell me if something happens (it is more general. a completion function is a kind of callback) e.g...
This question already has answers here:How to define a typedef struct containing pointers to itself?(2 answers)Closed9 years ago. if there a way to write this code with a typedef for the struct? ``` struct s_parola{ char info[40]; struct s_parola *next; }; ``` I tried with this code but it isn't correct: `...
If your problem is that you're receiving an "unknown type s_parola" within your struct, it's because you're trying to use the typedef before it's defined. You could do the following instead: ``` typedef struct s_parola s_parola; struct s_parola { char info[40]; s_parola *next; }; ```
So I've been asked to do that, and I did it like this: ``` #include <stdio.h> #include <stdlib.h> int main(void) { int N,i; printf("Give the number of char's you want to input.\n"); scanf("%d",&N); char *str = (char*) malloc(N); //this segment inputs the ...
I believe dynamic memory allocation using such asmalloc()is a better solution to your problem, that means instead of ``` char str[N+1]; ``` you should do ``` char *str = malloc(N+1); ``` And do not forget to free the memory byfree(str);after you finished use it.
I have a function which takes an integer input by the user. So I have: ``` scanf("%d, &x); ``` And then, the function: ``` test(int x); ``` Inside test(), I wanna check if the input is a digit or a character, so I tried: ``` if (isdigit(x)) // piece of code printf("Done!\n"); else printf("Bye!\n"); `...
You are passing integer not char! isdigit(x)check whetherxis a digit char e.g.'0','1'but not0,1what you are passing. It behaves like: ``` isdigit('h') returns 0 isdigit('1') returns 1 isdigit(1) returns 0 // your are passing this ``` Readmanual: Standard C Library Functions ...
This is a part of my code to explain my problem: ``` int64_t packet_tx=3; int64_t packet_rx=5; int64_t packet_loss; printf("Packet_loss: %d",((packet_tx-packet_rx)/packet_tx)*100); ``` In this code is everpacket_tx>=packet_rx; The result is an integer but the intermediate result is not an integer. How can i resolv...
Besides casting to double, you also need to use the format specifier for double,%lf, inprintf(). ``` printf("Packet_loss: %lf", ((double)(packet_tx-packet_rx)/(double)packet_tx)*100.0); ```
I have a minidump written to a file via:MiniDumpWriteDump. The file was sent to me from a client (i.e. I cannot use some sort of just-in-time debugger). My question is: how do I open it? Visual Studio gives the error: "Debugging older format crashdumps is not supported." I googled that and found that people were openi...
The tool:http://technet.microsoft.com/el-gr/sysinternals/dd996900.aspx A post you didn't see already in stackoverflow:Getting started with dump file analysis If you're still having a problem send me the minidump file. I was interested some time ago but reading these files is toooo frustrating! PS: Book i used:http:...
I want to write Arduino's data readings to a file locally on the computer. I MUST do this in C for a specific reason. Also, I am working in Windows 7 not Linux. I couldn't find any useful codes on the internet that satisfies my requirement. Can anyone help?
You should think aboutProcessingit uses the same IDE as the Arduino. It has common libraries for sending data back and forth between the Arduino and host PC. Where Processing is built on Java, its code that you write looks just like that of the Arduino's C++
``` #include <stdio.h> #include <string.h> #include <stdlib.h> //finds the number that is used only once void t(int c, int a[]){ int i,j; for(i=0;i<c;i++){ for(j=i+1;j<c;j++){ if(a[i]==a[j]){ a[i]=0; a[j]=0; } } } for(i=0;i<c;i++){ if(a[i]!=0) printf("%d\n",a[i])...
If a number appears three times (say), then when you find the first pair you set them equal to zero; that means you can't find the third appearance. If you know there's only supposed to be one unique number, you could perhaps count matches and then store the index if you get through the loop and don't find a match.
This question already has answers here:How does logical negation work in C?(5 answers)Closed9 years ago. I have ``` int x = 5; printf("%d", x); //i get 5... expected x = !x; printf("%d", x);// i get 0... hmm ``` 5 in binary is: 0101 if we apply the inverse to each bit, we should get 1010, but!is not necessarily an...
The not (!) operator returns either0or1, depending on whether the input is non-zero or0respectively. If you are looking for a bitwise negation, try~x.
let's say I did allocate place for an array of 3 chars using int *addr = malloc(3 * 1024); now I got place in memory for the array, how can I after that create the array that it goes to that allocated space? thank's in advance
``` int *addr = malloc(3 * 1024); ``` is not allocating space for3chars. The correct way is ``` char *addr = malloc(3); ``` Now you can put acharin the allocated space either by ``` addr[index] = 'c'; // here c stands for a char ``` or by ``` *addr = 'c'; ```
when I compile this code and I run it I get a result "PARENT" appears before the "CHILD". For information I'm on Linux Mint. ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> void main(){ pid_t pidc ; pidc = fork(); if(pidc < 0) {printf("error !\n");} else if(pidc == 0){ ...
Once you'veforked, the resulting two processes run largely independently. You don't get to assume the parent will run before the child (or vice versa) without adding some mechanism to force it to do so.
Well,l I am sorry. I think this question has already been answered somewhere else, but I could not find a solution for this. I have a variable of type int and an if-statement in C and I don't know what this statement checks. ``` int a; if(a==0x6634522) { //do some stuff } ``` I am really sorry if this is already a...
a==0x6634522checks whetherais equivalent to the hexadecimal0x6634522((6634522)16=(107169058)10) ) or not. It is checking the value stored ina, not the address ofa(&a).
For example, take open(2), which has the following synopsis: #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int open(const char *pathname, int flags); int open(const char *pathname, int flags, mode_t mode); int creat(const char *pathname, mode_t mode); Should I include all those header files or is ...
You should include all of them. The POSIX specification will tell you what's in each (for instance,thisis the POSIX specification for fcntl.h), or at least what's guaranteed to be in each.
i cannot figure out why NULL is not printed ``` #include "stdio.h" #include "stddef.h" typedef struct{ int info; struct DEMO1* next; } DEMO1; int main() { int temp; DEMO1 *head ; if(head==NULL) printf("NULL"); } ```
Memory is not initialized upon allocation. You cannot expect it to have a particular value until you set it.
I'm attempting to open a file which may or may not exist for read and write access. I'll also need to perform seek operations on this file. The issue I'm having is that the "r" file flag requires that the file exist, the "w" flag discards the existing contents, and the "a" flag disables seek operations by always appen...
Not possible to achieve it with single fopen call, since none of the modes available do what you want. I think that creating a file if it does not exist and then using r+ is the best option.
If i want to generateDIFFERENTrandom numbers in C between 0 and 1,000,000, would the following suffice? ``` srand(time(NULL)); int k = (rand() % 1000000; ``` from the output i'm seeing, only about 32767 different random numbers are being generated! Thanks!
rand int rand (void); Generate random number Returns a pseudo-random integral number in the range between 0 and RAND_MAX.RAND_MAXMaximum value returned by rand This macro expands to an integral constant expression whose value is the maximum value returned by the rand function.This valueis library-dependent, but ...
I am using Visual Studio 2013 on Windows 8.1, with OpenCV installed. I have copied the example hoghCircles() code and have built it, but I get an error in "line 1168" of xstring. Any help would be appreciated :) http://docs.opencv.org/doc/tutorials/imgproc/imgtrans/hough_circle/hough_circle.html
Since you haven't really provided much detail I am hazarding a guess here. Are you running the debug version from within the debugger? If so you need to go to the property pages of the project and add a command argument so it has an image to work with.
So, I have a simple c program on my Raspberry Pi, that is using the GPIO pins. When I compile it, i have to add-l bcm2835after the gcc for the library of the GPIO. Now I have another program which I have to compile with make, so I have to edit my Makefile to include thisbcm2835library. I know the basics of a makefil...
You can pass it as you would with any other flag. ``` #makefile CC=gcc CFLAGS= -g -c -Wall MYLIB= -lbcm2835 program: dependencies < TAB IT!>${CC} ${CFLAGS} ${MYLIB} -o Obj dependencies ```
I'm building some modular function and I'm not getting why I get a segmentation fault after freeing my module. My .h file ``` void StringInit(String *this, char const *s) { this->str = strdup(s); printf("%s\n", this->str); } void StringDestroy(String *this) { if(this == NULL || this->str == NULL) ...
You have to call free forthis->str, not forthis(because you allocated a new string withstrdup). Moreover set a member toNULLdoesn't free it: ``` if (this == NULL || this->str == NULL) return; free(this->str); this->str = NULL; ``` Everything else in your code works as expected, you can allocate objects on stack...