question
stringlengths
25
894
answer
stringlengths
4
863
Is there a way to list all the installed libraries and/or query if a specific library is installed with gcc? I want to know if glut is available on my system (without browsing all the library path). I am using mingw w/ gcc 4.5.2 under windows.
The way to check will generally be platform and compiler dependent. Getting it 100% right is hard. You can use a build system likeCMakefor generating your actual build system (confused yet;-)?) I founda small tutorialwhich explains how to find glut for you. Essentially, all you need is ``` find_package(GLUT) ``` i...
I have these codes ``` #include<stdio.h> void main() { int a; scanf("%d",&a); printf("%d",(int)a); } ``` My question is,when i type a as an input,i get 45 as ASCII equivalent and now i decided to change these codes to: ``` #include<stdio.h> void main() { int a; scanf("%c",&a); printf("%d",...
When you enter achartoint a; scanf("%d",&a);, it skips taking the input. Thecharstays in the input buffer and the previous value ofais retained. So in your case,45is the initial garbage value ofa. However, when you input as a character as inint a; scanf("%c",&a);, the character is taken from the input buffer, and its...
Usually auint64_tor auint32_t/uint16_tetc can be retrieve from achar* bufas follows: ``` uint32_t val = *(uint32_t*) buf; ``` But now supposebufischar [6], how would one retrieve a numerical value from it? *Unsigned big endian (network byte order)
A portable and standard-conforming way (in contrast to pointer casting or memcpy) would be to make it explicit: ``` uint64_t val = 0; for (int i = 0; i < 6; ++i) val |= (uint64_t)(unsigned char)buf[i] << (8*(6-i-1)); ``` This assumes big-endianess (network byte order). The extra cast tounsigned charis a hack tha...
Can you please tell me what is wrong with the following code ? For some reason the compiler refuses to recognize the O_DIRECT flag. ``` #define _GNU_SOURCE #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> int main(int argc, char **argv) { int fd; fd = open(...
Don't worry about it. It's just the indexing parser which decides the text editor syntax highlighting and (ideally) links identifiers to definitions. You can resolve the problem by dumping the predefined macros from the compiler and feeding them into the indexing configuration control panel. Also double check that it...
While I was reading through glibc source code, I found this interesting comment in strcat.c . Can anyone explain how does this optimization work? ``` /* Make S1 point before the next character, so we can increment it while memory is read (wins on pipelined cpus). */ s1 -= 2; do { ...
Pipelined CPU's can do some things in parallel. For instance, it can increment the address of S1, while reading from the address it used to point at.
I know you can achieve o(n) in a sorted sets but I have looked around stackoverflow and couldn't find any answer that would be in o(n) efficiency, only o(n^2). Is there a way to achieve o(n) or is it impossible?
If the unordered sets have O(1) lookup (e.g. hash_maps) then you can iterate over set A, and for each item in set A, do a lookup in set B to see if it also contains the same item. That results in O(n) for the full operation. (Btw don't forget to check the sizes of the two sets first -- if they are different sizes, y...
I have an audio driver present in linux kernel that i have. Using alsa utilities like aplay, set and get i want to write a c application to test driver's functionalities like playback, set volume and get volume. I have a confusion that how to use aplay and other alsa commands in a c code. I am doing it for the very fi...
Please see the answer to this question: Set ALSA master volume from C code And also read the alsa/mixer lib manpage. Other references:http://www.alsa-project.org/alsa-doc/alsa-lib/mixer_8h.html
I'm reading a book. The author explains the function clearly. The problem is that my program doesn't detect any key that is pressed, so I can't terminate the window or stop a loop. This is the part of the problem. ``` while(1) { frame = cvQueryFrame( capture ); if ( !frame ) break;...
There might be 2 possibilities , The focus is not on the cv window when you press the key.Try using just, cvWaitKey().
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...
It doesn't mean anything. It's just an extra semicolon. You can delete it (leaving a single semicolon) without any effect on your program.
I cannot get the exponential to work with user input. Every time user is prompted to add input, after the input is entered the program immediately closes. ``` #include <stdio.h> #include <stdlib.h> #include <math.h> int main() { double input = 0; double exp_val; printf("Plese enter the exponent to check for...
Besides @happydave's answer to use&input, you also need the%lfformat specifier to read a double: ``` scanf("%lf", &input); ``` Check outWhy does scanf() need "%lf" for doubles, when printf() is okay with just "%f"? After this, you should get the correct answer, see it live:http://ideone.com/246clu.
I want to move a pointer forward one byte. But I get this error: ``` lvalue required as increment operand ``` With this code: ``` int **test = 0; ((char *) *test)++; ``` But it is fine with this: ``` int **test = 0; char **t2 = (char **) test; (*t2)++; ``` How do I do the latter concisely?
If you want to increment the value pointed to by a double pointer: ``` (* (char **) test)++; ``` which means de-refrence the double pointer named "test" and then increment the value it is currently pointing to. That will increment the value the pointer is pointing too, not advance the pointer itself. That's what I ...
I am getting segmentation fault while running this program. Using gdb, I have confirmed that it is at thepthread_createcall. ``` #include <stdio.h> #include <pthread.h> struct point { int x; int y; char name; }; void *start (void * P) { while (1) { } } main() { struct point P; P.name = 'P'; P.x = ...
You defined a pointerpthread_t *tid, but never give it a valid value, change it to: ``` pthread_t tid; pthread_create (&tid, NULL, (void *) start, (void *) &P); ```
I am having the hardest time trying to figure out how to use a text file that is passed in as a command line argument. I simply dont know to get the file text into my program to be used. My code looks something like this.... ``` char buffer[80]; int i; int lineCount = 0; fgets(buffer, 80, stdin); //ge...
Use argv[1]. That will give you the file name, then you can use fopen() and use file operations to read the contents from the file.
What 16-bit hexadecimal signed int value works with this code: ``` #include <stdio.h> int main() { while (1) { int i; if (scanf("%x", &i) != 1) break; printf("%d %s -%d\n", i, (i == -i) ? "==" : "!=", i); } return 0; } ``` There must be some value with which this returns "==", other than "0".
8000(hex) would be the answer (on a 16-bit machine). It's because when you negate8000in 2's complement, you take the complement plus 1, so that's7FFF + 1or back to8000. In decimal representation, the number is,-32768. In the case of the given code, this would be trueifanintis 16 bits for the given compiler and proce...
In K&R, I saw an example where a string can be concatenated with a space" ``` char *s = "abc" "foo"; printf("%s", s); // prints "abcfoo" ``` How is space string concatenation different from using strcpy and strcat?
Adjacent string literal are concatenated by the pre-processor. From thedraft C99 standardsection5.1.1.2Translation phasesparagraph6: Adjacent string literal tokens are concatenated so it creates one string literal as a result.
I'm looking for an easy way to trigger a real page fault (and not a segfault resulting from accessing an already mapped address or a protected address). What could be one? I thought of simply run ``` int main(void) { int *x = 1000; *x = 2000; } ``` But it does not seem to result in a page fault but rather ...
I believemmap()a disk file, and read from or write to it should be enough. At least it is enough on Linux.
It's been ages since I last worked with C++. Situation: I have a large array that needs to be available in different.cppfiles. It is immutable, so I thought I better put aconst char array[] = …in the header file. But now the array appears several times in the compiled binary, as far as I can see. What is the prope...
If you define an array in a header file (whether or not you initialise it), you will get lots of copies. You want to declare it in the header: ``` extern const char array[]; ``` and define it like this in your.c/.cppfile: ``` const char array[] = ... ; ```
I've seen the below macro used in a lot of cache.h files: ``` #define alloc_nr(x) (((x)+16)*3/2) ``` Hereis one example. I know it's used to increase allocated buffer size when the buffer is almost full. The buffer would grow by roughly 1.5 times its current size. That's why*3/2is used. But why an extra16is added? ...
If the initial value is 0, you wantalloc_nr(0)to give a strictly positive number (24 here). Without the16it would be 0. You wantalloc_nr(x)to be greater thanx(and not too near ofxto avoid too frequent reallocations). The particular numbers16and3and2are not very important (the ratio3/2is more significant).
I have a script that reads in a file using a while loop. One IF statement reads the line (it is a csv file) then a second checks for a match. ``` while ( file != NULL ) { if ( sscanf to read the line ) { if ( to check for matches) { toggle variable break; } ...
Abreakorcontinuestatement is for the nearestloop. Theifstatements are not even considered. The exception of course beingbreakwithin aswitchstatement.
Is there a way to use a preprocessor directive without using the # character in C code? Can we echo the hash character somehow by using its ASCII etc. equivalents? Eg:1can be echoed by using'SOH'in the .c source file. Is there a similar hack for'#'?
You can use the digraph or trigraph equivalent if your compiler supports them (you may need to pass flags to the compiler): digraph:%: trigraph:??= However, if you're trying to use preprocessor macros to generate preprocessor commands, there's no way to do that.
While I was reading through glibc source code, I found this interesting comment in strcat.c . Can anyone explain how does this optimization work? ``` /* Make S1 point before the next character, so we can increment it while memory is read (wins on pipelined cpus). */ s1 -= 2; do { ...
Pipelined CPU's can do some things in parallel. For instance, it can increment the address of S1, while reading from the address it used to point at.
I know you can achieve o(n) in a sorted sets but I have looked around stackoverflow and couldn't find any answer that would be in o(n) efficiency, only o(n^2). Is there a way to achieve o(n) or is it impossible?
If the unordered sets have O(1) lookup (e.g. hash_maps) then you can iterate over set A, and for each item in set A, do a lookup in set B to see if it also contains the same item. That results in O(n) for the full operation. (Btw don't forget to check the sizes of the two sets first -- if they are different sizes, y...
I have an audio driver present in linux kernel that i have. Using alsa utilities like aplay, set and get i want to write a c application to test driver's functionalities like playback, set volume and get volume. I have a confusion that how to use aplay and other alsa commands in a c code. I am doing it for the very fi...
Please see the answer to this question: Set ALSA master volume from C code And also read the alsa/mixer lib manpage. Other references:http://www.alsa-project.org/alsa-doc/alsa-lib/mixer_8h.html
I'm reading a book. The author explains the function clearly. The problem is that my program doesn't detect any key that is pressed, so I can't terminate the window or stop a loop. This is the part of the problem. ``` while(1) { frame = cvQueryFrame( capture ); if ( !frame ) break;...
There might be 2 possibilities , The focus is not on the cv window when you press the key.Try using just, cvWaitKey().
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...
It doesn't mean anything. It's just an extra semicolon. You can delete it (leaving a single semicolon) without any effect on your program.
I cannot get the exponential to work with user input. Every time user is prompted to add input, after the input is entered the program immediately closes. ``` #include <stdio.h> #include <stdlib.h> #include <math.h> int main() { double input = 0; double exp_val; printf("Plese enter the exponent to check for...
Besides @happydave's answer to use&input, you also need the%lfformat specifier to read a double: ``` scanf("%lf", &input); ``` Check outWhy does scanf() need "%lf" for doubles, when printf() is okay with just "%f"? After this, you should get the correct answer, see it live:http://ideone.com/246clu.
Hello StackOverflow community. I am actually working on a project trying to emulate a very basic shell. I have an exit builtin that take a parameter and based on this I need to return the correct value (value % 256) For example :exit 42 will return 42 exit 300 will return 44 But I can't find exactly how this is exa...
C standard leaves most things about the return values ofmainto be defined by the implementation. Basically returning0,EXIT_SUCCESS, orEXIT_FAILUREis somehow standard and reliable, everything else depends on the platform. In this case it seems like the operating system gives you the value modulo 256 (as anuint8_t).
In this program I am getting segmentation fault due to line: ``` fgets( string , 50, in ); ``` If I comment it out the program exits fine but I am not sure what I am doing wrong with it? I checked the declaration of function fgets which seems fine for the program. ``` //char *fgets(char *str, int n, FILE *stream) ...
fopen()might not have been successful, check the return value of that before you try to read.
I want to know how to pass a value into a program like: cat somefile | myprog somefile: hello $cat somefile | myprog >hello this is what I tried. ``` int main(int argc, char **argv) { printf("%s", argv[1]); return 0; } ``` I doubt it's complicated but I Just don't know how. P.S my keyboard is boarderline br...
If you want your examplecat foo | barto work, you need to read data from standard input, e.g.: ``` #include <stdio.h> int main() { int ch; while ( (ch = getchar()) != EOF ) putchar(ch); } ``` This program just echoes everything coming form standard input to standard output, so ``` $ cat somefile | myprog `...
Our coding style is we pass a pointer to a struct to a function, when we are modifying the contents of the structure. However, when we are not modifying the contents of a struct, is there still any reason to prefer passing a pointer to a struct to a function?
The advantage is in the size being passed: when you pass a largestruct, the compiler generates code to make a copy of thatstructif you pass it by value. This wastes CPU cycles, and may create a situation when your program runs out of stack space, especially on hardware with scarce resources, such as embedded microcont...
This question already has answers here:Character size in Java vs. C(5 answers)Closed9 years ago. I've stumbled on this while learning JAVA I've noticed that char takes 16 bit , while I remember that it takes 8 in C. can someone explain why they are not resemble ?
C# chars are Unicode, which is 16-bit, while C only uses ASCII, which is actually only 7 bits.
in ICMP header they are filling the checksum with the following statement i found ICMP_ECHO value as 8 ``` icmp->checksum = htons(~(ICMP_ECHO << 8)); ``` can anyone tell me what exactly it will do and how it will fill the details of checksum
TheICMPchecksum is anRFC 1071 checksum: (1) Adjacent octets to be checksummed are paired to form 16-bit integers, and the 1's complement sum of these 16-bit integers is formed.(2) To generate a checksum, the checksum field itself is cleared, the 16-bit 1's complement sum is computed over the octets concerned, and t...
how can I sscanf the following string empty(1) empty(20) I tried the following but always failed ``` int count; sscanf(buf, "%*s(%d)", &count) ``` Thanks in advance!
change to ``` sscanf(buf, "%*[^(](%d", &count); ```
This is an interview question but I do not know how to do it. Suppose we have a local static variable declared in a function. The interviewer asked me without calling the function, is it possible to modify it? I do not know how. But I suppose probably we can get the address of the local static variable by some way?
It's allowed to return a pointer to an object with static storage, e.g. ``` #include <stdio.h> int *foo(void) { static int x; printf("%d\n", x); return &x; } int main(void) { int *p = foo(); *p = 10; foo(); return 0; } ``` Will print: ``` 0 10 ``` Alternatively, you could of course pa...
I want to know that if there is any difference in storage allocation and memory allocation in c and what exactly is storage allocation??
In C the wordstorageis usually used in the context ofstorage classof a variable:auto,static,extern,register, which specifies the way memory will be allocated the variable. Memory allocation can bestatic, automatic, and dynamic. In general sense 'storage' means just memory. So in your context I think they are synonym...
This question already has answers here:Character size in Java vs. C(5 answers)Closed9 years ago. I've stumbled on this while learning JAVA I've noticed that char takes 16 bit , while I remember that it takes 8 in C. can someone explain why they are not resemble ?
C# chars are Unicode, which is 16-bit, while C only uses ASCII, which is actually only 7 bits.
in ICMP header they are filling the checksum with the following statement i found ICMP_ECHO value as 8 ``` icmp->checksum = htons(~(ICMP_ECHO << 8)); ``` can anyone tell me what exactly it will do and how it will fill the details of checksum
TheICMPchecksum is anRFC 1071 checksum: (1) Adjacent octets to be checksummed are paired to form 16-bit integers, and the 1's complement sum of these 16-bit integers is formed.(2) To generate a checksum, the checksum field itself is cleared, the 16-bit 1's complement sum is computed over the octets concerned, and t...
how can I sscanf the following string empty(1) empty(20) I tried the following but always failed ``` int count; sscanf(buf, "%*s(%d)", &count) ``` Thanks in advance!
change to ``` sscanf(buf, "%*[^(](%d", &count); ```
This is an interview question but I do not know how to do it. Suppose we have a local static variable declared in a function. The interviewer asked me without calling the function, is it possible to modify it? I do not know how. But I suppose probably we can get the address of the local static variable by some way?
It's allowed to return a pointer to an object with static storage, e.g. ``` #include <stdio.h> int *foo(void) { static int x; printf("%d\n", x); return &x; } int main(void) { int *p = foo(); *p = 10; foo(); return 0; } ``` Will print: ``` 0 10 ``` Alternatively, you could of course pa...
I want to know that if there is any difference in storage allocation and memory allocation in c and what exactly is storage allocation??
In C the wordstorageis usually used in the context ofstorage classof a variable:auto,static,extern,register, which specifies the way memory will be allocated the variable. Memory allocation can bestatic, automatic, and dynamic. In general sense 'storage' means just memory. So in your context I think they are synonym...
in ICMP header they are filling the checksum with the following statement i found ICMP_ECHO value as 8 ``` icmp->checksum = htons(~(ICMP_ECHO << 8)); ``` can anyone tell me what exactly it will do and how it will fill the details of checksum
TheICMPchecksum is anRFC 1071 checksum: (1) Adjacent octets to be checksummed are paired to form 16-bit integers, and the 1's complement sum of these 16-bit integers is formed.(2) To generate a checksum, the checksum field itself is cleared, the 16-bit 1's complement sum is computed over the octets concerned, and t...
how can I sscanf the following string empty(1) empty(20) I tried the following but always failed ``` int count; sscanf(buf, "%*s(%d)", &count) ``` Thanks in advance!
change to ``` sscanf(buf, "%*[^(](%d", &count); ```
This is an interview question but I do not know how to do it. Suppose we have a local static variable declared in a function. The interviewer asked me without calling the function, is it possible to modify it? I do not know how. But I suppose probably we can get the address of the local static variable by some way?
It's allowed to return a pointer to an object with static storage, e.g. ``` #include <stdio.h> int *foo(void) { static int x; printf("%d\n", x); return &x; } int main(void) { int *p = foo(); *p = 10; foo(); return 0; } ``` Will print: ``` 0 10 ``` Alternatively, you could of course pa...
I want to know that if there is any difference in storage allocation and memory allocation in c and what exactly is storage allocation??
In C the wordstorageis usually used in the context ofstorage classof a variable:auto,static,extern,register, which specifies the way memory will be allocated the variable. Memory allocation can bestatic, automatic, and dynamic. In general sense 'storage' means just memory. So in your context I think they are synonym...
What is the C equivalent ofstd::pairfrom C++? I'm trying to find the equivalent on the web and can't find anything but explanations of what it does.
There isn't one.std::pairis a template, and C doesn't have anything similar to templates. For a given specialisation of the template, you can define a structure that's more or less equivalent; so thatstd::pair<int, double>is similar to ``` struct pair_int_double { int first; double second; }; ``` but you've...
I am writing a shell with both interactive and batch modes in C. I would like to print the prompt in interactive mode and don't show it in batch mode. i.e. ``` bash> ./myshell ``` should show prompt, and ``` bash> ./myshell < sample.txt ``` should only show the output from the commands in "sample.txt", but not th...
isatty(3)can be used to determine if a given file descriptor is atty. Shells will use this to determine what kind of input to expect. For example: ``` if (isatty(STDIN_FILENO)) { // Interactive shell } else { // Redirected stdin } ```
I'm working on solving the Producer/Consumer problem through different methods. The one I'm currently working on involves my own implementation of a semaphore, paired with Peterson's solution to protect the semaphore's down() and up() function calls. The problem is, I'm working in C, and the only way I can think of c...
You will likely want to use some OS-provided or hardware-provided synchronization primitive. Examples include system calls (e.g. Linux'sfutexcall, Windows'EnterCriticalSection), hardware swap calls (e.g.cmpxchgon x86,ldrex/strexon ARM), or library functions which use one of these methods (e.g.pthread_mutex). Trying t...
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 So I was wondering why C++ allows for C keywords to be used. After all,printf("Hello...
This is because C++ was designed to allow for as much compatability with C code as possible. It allows it to be more extensible, and easily adopted into applications previously written in pure C.
``` typedef struct { int id = 0; char *name = NULL; char *department = NULL; int phone = 0; } emp; ``` In C programming is it a good programming practice to do something like that, or, should I initialize when I declare the variable 'emp'. I am using a GCC compiler and the above code does compile. I ...
Withtypedef struct { ... } emp;you are creating a new complex type called "emp". When you declare a variable of type "emp", that is where you typically initialize it. I would go with: ``` typedef struct { int id; char *name; char *department; int phone; } emp; emp myVar = { /* id */ 0, /* name */ NUL...
I am looking for something to copy a 2D array into another (larger) 2D array extremely fast, using SSD/MMX/3DNow/SIMD (Whatever). I do not want to implement myself, just looking for a high-optimized supported and maintained solution. I am using Clang(++) on Linux. ``` memcyp2Di(int *src, int *dest, int srcw, int srch...
Take a look atAsmlibby Agner Fog, it provides an extremely optimized version of memcpy and other common libc functions written in assembly and using the best SIMD instruction set available in your CPU, from basic SSE all the way up to the latest AVX2 and FMA3 instructions found in Haswell processors, for instance.
code sample(foo.c) ``` int main(){ int *x=(int*)malloc(sizeof(int)); // break here *x=10; free(x); return 0; } ``` I want to break at malloc. Here is what I try: ``` # gcc -g foo.c -o bar # gdb bar (gdb) b main Breakpoint 1 at 0x80484cf: file src.c, line 7. (gdb) r Breakpoint 1, main () at src.c:7 (gdb) b mall...
I cannot reliably reproduce the error, but on Linux you could try breaking at__libc_mallocinstead ofmalloc.
I'm learning buffer overflow exploiting. I wrote a vulnerable program like this: ``` #include <stdio.h> #include <string.h> main(int argc, char *argv[]) { char buffer[80]; strcpy(buffer, argv[1]); return 1; } ``` Very simple program. The idea is to overwrite the return address that's used to return to t...
You probably have a no-execute stack, which prohibits code from being executed from certain address ranges. You need to compile with-z execstackto force the stack to be executable.
I am working on a bit complex project, and i wonder is it possible to debug just part of code not entire application because its too slow. Like i write some lines and code, compile, and then tell to debugger from where to start execution and to assign variable values manually.
This is only possible if you set up the environment for your part of code which will model the real project. Look atmock objects(brief description).
I cannot find the answer to this in my book anywhere. the second printf statement prints x: 75 y: 0 and I cannot figure out why. please help ``` #include<stdio.h> Int scaleBack(int); Void setValues(int*, int*, int); Int main() { Int x = 75; Int y = 17; Int factor; Factor = scaleBack(x / y); se...
The value of(quotient + 2) % (quotient + 1)is 1 for every positive value ofquotient. So your call to functionscaleBackreturns 1, and your call to functionsetValuessetsyto 0.
Now I know from this post aboutassigning one struct to anotherthat I can assign a struct variable to another one of the same type and ashallowcopy will happen. ``` struct Test t1; struct Test t2; t2 = t1; ``` But what if I do this? ``` struct Test *t1; struct Test *t2; t1 = malloc(sizeof(struct Test)); t2 = malloc(...
the following ``` *t2 = *t1; ``` will indeed be doing a shallow copy. Basically, the*operators on pointers act as if you were using the pointed value. But be sure to allocate memory and define values for those or you'll get an undefined behavior.
I'm trying to convince gcc (4.8.1) or clang (3.4) to vectorize the following code on a ivy bridge processor: ``` #include "stdlib.h" #include "math.h" float sumsqr(float *v, float mean, size_t n) { float ret = 0; for(size_t i = 0; i < n; i++) { ret += pow((v[i] - mean), 2); } return ret; } ``...
Thepowfunction is very general and it may not be visible to the compiler what it does (remember that it can compute things likepow(1.8, -3.19). So it might help to use only builtin operations, and not make function calls: ``` for(size_t i = 0; i < n; i++) { float const x = v[i] - mean; ret += x * x; } ```
program in c language ``` void main() { char *a,*b; a[0]='s'; a[1]='a'; a[2]='n'; a[3]='j'; a[4]='i'; a[5]='t'; printf("length of a %d/n", strlen(a)); b[0]='s'; b[1]='a'; b[2]='n'; b[3]='j'; b[4]='i'; b[5]='t'; b[6]='g'; printf("length of b %...
You are assigning to pointer (which contains garbage) without allocating memory. What you are noticing isUndefined Behavior. Alsomainshould return anint. Also it does not make sense to try and find the length of an array of chars which are notnulterminated. This is how you can go about: Sample code
In the Linux kernel,long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)is used to assign a function running on a specific CPU core. Is there any equivalent user-space function?
No, there is not, the execution contexts provided by the kernel are quite different than that of the user space. What you can do is. pthread_create() a new thread.Pin that thread to a particular CPU, with pthread_setaffinity_np() If you need a similar API to what the kernel have, you need to create a small pool of ...
Let's say I have a2D arrayand I want to pass it'sith column to asort functionthat takes in a1D arrayand sorts it. Can it be done without copying the column to anotherarrayinC/C++language. I am concerned about reducingtime and spaceused. (Ofcourse thecomplexityremains same)
I suppose that bysortyou meanstd::sortfrom STL, which takes random access iterators. So all you need to do is provide column iterators. You can either implement one by yourself (example), use some iterator library (ie.Boost.Iterator) or use some matrix implementation which provides row/column iterators.
As we know PyObject_AsReadBuffer was changed in version2.5. On v2.4, we can use it like this, ``` int bufferLength = 0; const void* buffer = NULL; PyObject_AsReadBuffer(pyObj, &buffer, &buffer_len); ``` But I have to modify it like this to run on v2.7, ``` Py_ssize_t bufferLength = 0; const void* buffer = NULL; P...
in include/python2.7/patchlevel.h ``` #define PY_MAJOR_VERSION 2 #define PY_MINOR_VERSION 7 ``` So we can use PY_MAJOR_VERSION PY_MINOR_VERSION to compare the version
``` #include<stdio.h> #include<conio.h> #include<stdlib.h> int main() { char a[100]; int c, e=0; char d; printf("enter a text of your choice\n"); scanf("%s",a); printf("enter the vowel you want to know its occurence\n"); fflush(stdin); scanf("%c",&d); for(c=0;c<strlen(a);c++) { ...
You read in the vowel in the variabledbut then never make use of it, so you will get the counts of all vowels in your input text, provided there are no other bugs in the code.
``` #include <stdio.h> #include <time.h> int main (void) { double diff = 0.0; time_t start; time_t stop; time(&start); print("Enter millisecond to stop"); ``` so what is code should add to stop timer after given interval of timer
``` int seconds; scanf ("%d",&seconds); stop = 0; while (stop < start + seconds) time(&stop); ```
In the following code: ``` int main() { int i; char* s = "Hello"; i = 10; } ``` In memory: 10should go in stackaddress of"hello"should go in stack"Hello"should be stored in read only memory In the process memory, where isiands. Where do they reside?
The variable names are just a convenience for the programmer, so that he can refer to them. The values themselve are stored wherever the compiler sees fit to place them, but the names are discarded. If the optimizer decides that a certain variable has a small enough scope and there are enough registers available, the...
unsigned char networkMask [sizeof (struct in6_addr)] = { [0 ... (sizeof (struct in6_addr) - 1)] = 0xff }; what does(0...(sizeof))is representing here. How this array is allocated.
This particular syntax is a GCC extension of thedesignated initializer. With it, you can initialize an array like this: ``` unsigned char foo[<n>] = { [0 ... <n> - 1] = <k> }; ``` Whereby<n>is the number of members and<k>is any given member value. In the code you have shown, it initializes thenetworkMaskarray with0...
I need to find out the name of thefilesystemandmount directoryname from a given subdirectory name on LINUX(CentOS 5.4). ``` #include <stdio.h> #include <sys/vfs.h> #include <sys/mount.h> int main(int argc, char** argv) { struct statfs ls_tbs_fs; statfs(argv[1], &ls_tbs_fs); printf("TOTAL DISK KB : %lu\n...
Usestat(2),statfs(2)andstatvfs(2). Then read and parse/proc/self/mountsand/proc/self/mountstats. Try also tostrace dfto find out what syscalls it is doing.
Code goes first: ``` struct yo { char *name; int several[10]; int num; }; int main(void) { struct yo *test_yo = malloc(sizeof(struct yo)); printf("%p\t%p\t%p\n", (void *)&test_yo->name, (void *)&test_yo->num, (void *)&test_yo->several); return 0; } ``` My question is: If malloc only allocate...
The compiler works that out. i.e.sizeofworks out the space required and the compiler works out how to arrange the various items in that memory
I would like to change the value of the third letter in apple to "a". Using the indirection this way gives me a compiler error saying: invalid type argument of unary ‘*’ (have ‘int’) ``` #include<stdio.h> int main(){ char c[6]="apple"; *c[2]="a"; return 0; } ```
You should use the following: ``` c[2]='a'; ``` In C and C++"x"is a type ofconst char [2]. To specify a character you need to use'x'that is a type ofconst char.
How does this C/C++ code work? I understood most of it but not the part specified below: ``` c2= (c1>='a' && c1<='z') ? ('A'+c1-'a'):c1 ``` Especially this part: ``` ('A'+c1-'a') ``` What is this part of the code doing? Bothc1andc2have typechar.
The code converts a lower case character to upper case. If the character isn't lower case then it returns the original character. The expression('A'+c1-'a')does the conversion.c1-awill give the 0-based position of the character within the alphabet. By adding this value toAyou will get the upper case equivilant ofc1. ...
I have a text file(unsigned short values) as follows abc.txt ``` 2311 1231 1232 54523 32423 ``` I'm reading this file in my function using while loop and storing in a buffer as follows ``` while(!feof(ref)) { fscanf(ref,"%d\n",&ref[count]); count++; } ``` It is taking too much time for reading large file ...
This is because secondary memory access is slower than primary memory access. First dump the file into primary memory usingfread()in binary mode. Then read from primary memory integer by integer.
I have char[] as such ``` char string[] = "Hello world !!!"; ``` when I'm trying to reallocate it's memory I'm getting error ``` realloc(string, 50); // error here ```
You can onlyreallocthings youmalloc/calloc/realloc'ed. Achararray is not any of those things, so it is normal for you to get an error in this case.
Now I know from this post aboutassigning one struct to anotherthat I can assign a struct variable to another one of the same type and ashallowcopy will happen. ``` struct Test t1; struct Test t2; t2 = t1; ``` But what if I do this? ``` struct Test *t1; struct Test *t2; t1 = malloc(sizeof(struct Test)); t2 = malloc(...
the following ``` *t2 = *t1; ``` will indeed be doing a shallow copy. Basically, the*operators on pointers act as if you were using the pointed value. But be sure to allocate memory and define values for those or you'll get an undefined behavior.
I'm trying to convince gcc (4.8.1) or clang (3.4) to vectorize the following code on a ivy bridge processor: ``` #include "stdlib.h" #include "math.h" float sumsqr(float *v, float mean, size_t n) { float ret = 0; for(size_t i = 0; i < n; i++) { ret += pow((v[i] - mean), 2); } return ret; } ``...
Thepowfunction is very general and it may not be visible to the compiler what it does (remember that it can compute things likepow(1.8, -3.19). So it might help to use only builtin operations, and not make function calls: ``` for(size_t i = 0; i < n; i++) { float const x = v[i] - mean; ret += x * x; } ```
program in c language ``` void main() { char *a,*b; a[0]='s'; a[1]='a'; a[2]='n'; a[3]='j'; a[4]='i'; a[5]='t'; printf("length of a %d/n", strlen(a)); b[0]='s'; b[1]='a'; b[2]='n'; b[3]='j'; b[4]='i'; b[5]='t'; b[6]='g'; printf("length of b %...
You are assigning to pointer (which contains garbage) without allocating memory. What you are noticing isUndefined Behavior. Alsomainshould return anint. Also it does not make sense to try and find the length of an array of chars which are notnulterminated. This is how you can go about: Sample code
In the Linux kernel,long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)is used to assign a function running on a specific CPU core. Is there any equivalent user-space function?
No, there is not, the execution contexts provided by the kernel are quite different than that of the user space. What you can do is. pthread_create() a new thread.Pin that thread to a particular CPU, with pthread_setaffinity_np() If you need a similar API to what the kernel have, you need to create a small pool of ...
Let's say I have a2D arrayand I want to pass it'sith column to asort functionthat takes in a1D arrayand sorts it. Can it be done without copying the column to anotherarrayinC/C++language. I am concerned about reducingtime and spaceused. (Ofcourse thecomplexityremains same)
I suppose that bysortyou meanstd::sortfrom STL, which takes random access iterators. So all you need to do is provide column iterators. You can either implement one by yourself (example), use some iterator library (ie.Boost.Iterator) or use some matrix implementation which provides row/column iterators.
As we know PyObject_AsReadBuffer was changed in version2.5. On v2.4, we can use it like this, ``` int bufferLength = 0; const void* buffer = NULL; PyObject_AsReadBuffer(pyObj, &buffer, &buffer_len); ``` But I have to modify it like this to run on v2.7, ``` Py_ssize_t bufferLength = 0; const void* buffer = NULL; P...
in include/python2.7/patchlevel.h ``` #define PY_MAJOR_VERSION 2 #define PY_MINOR_VERSION 7 ``` So we can use PY_MAJOR_VERSION PY_MINOR_VERSION to compare the version
``` #include<stdio.h> #include<conio.h> #include<stdlib.h> int main() { char a[100]; int c, e=0; char d; printf("enter a text of your choice\n"); scanf("%s",a); printf("enter the vowel you want to know its occurence\n"); fflush(stdin); scanf("%c",&d); for(c=0;c<strlen(a);c++) { ...
You read in the vowel in the variabledbut then never make use of it, so you will get the counts of all vowels in your input text, provided there are no other bugs in the code.
``` #include <stdio.h> #include <time.h> int main (void) { double diff = 0.0; time_t start; time_t stop; time(&start); print("Enter millisecond to stop"); ``` so what is code should add to stop timer after given interval of timer
``` int seconds; scanf ("%d",&seconds); stop = 0; while (stop < start + seconds) time(&stop); ```
In the following code: ``` int main() { int i; char* s = "Hello"; i = 10; } ``` In memory: 10should go in stackaddress of"hello"should go in stack"Hello"should be stored in read only memory In the process memory, where isiands. Where do they reside?
The variable names are just a convenience for the programmer, so that he can refer to them. The values themselve are stored wherever the compiler sees fit to place them, but the names are discarded. If the optimizer decides that a certain variable has a small enough scope and there are enough registers available, the...
unsigned char networkMask [sizeof (struct in6_addr)] = { [0 ... (sizeof (struct in6_addr) - 1)] = 0xff }; what does(0...(sizeof))is representing here. How this array is allocated.
This particular syntax is a GCC extension of thedesignated initializer. With it, you can initialize an array like this: ``` unsigned char foo[<n>] = { [0 ... <n> - 1] = <k> }; ``` Whereby<n>is the number of members and<k>is any given member value. In the code you have shown, it initializes thenetworkMaskarray with0...
I need to find out the name of thefilesystemandmount directoryname from a given subdirectory name on LINUX(CentOS 5.4). ``` #include <stdio.h> #include <sys/vfs.h> #include <sys/mount.h> int main(int argc, char** argv) { struct statfs ls_tbs_fs; statfs(argv[1], &ls_tbs_fs); printf("TOTAL DISK KB : %lu\n...
Usestat(2),statfs(2)andstatvfs(2). Then read and parse/proc/self/mountsand/proc/self/mountstats. Try also tostrace dfto find out what syscalls it is doing.
Code goes first: ``` struct yo { char *name; int several[10]; int num; }; int main(void) { struct yo *test_yo = malloc(sizeof(struct yo)); printf("%p\t%p\t%p\n", (void *)&test_yo->name, (void *)&test_yo->num, (void *)&test_yo->several); return 0; } ``` My question is: If malloc only allocate...
The compiler works that out. i.e.sizeofworks out the space required and the compiler works out how to arrange the various items in that memory
``` char r[40]; strcpy(r,"abcdef"); strcat(r,r); ``` My program crashes at the third line? Replacing strcat(r,r); by strcat(r,"abcdef"); works fine though.... why is that?
According tostrcat(3): Thestrcat()function appends the src string to the dest string, overwriting the terminating null byte ('\0') at the end of dest, and then adds a terminating null byte.The strings may not overlap, and the dest string must have enough space for the result.
I wrote the following C program in Visual Studio 2013: ``` #include <stdio.h> int main(){ int number; int fibonacci(int number); printf("please enter number\n"); scanf_s("%d", &number); printf(fibonacci(number)); return 0; } int fibonacci(number){ if (number == 1 || number == 0){ return number; ...
``` printf(fibonacci(number)); ``` should be ``` printf("%d", fibonacci(number)); ``` or even better ``` int result = fibonacci(number); printf("%d", result); ```
This question already has answers here:Sum of even numbers errors(3 answers)Closed9 years ago. I'm getting the following errors: ``` evenSum.c:9:11: error: subscripted value is neither array nor pointer nor vector if(array[i] % 2 ==0) ^ evenSum.c:12:15: error: subscripted value is neither array nor pointer...
To use it as an array it should be: int Even_Sum(int *array, int i) or int Even_Sum(int array[], int i) regardless of what you are trying to do in the rest of the algorithm.
my question is about ``` gets() ``` and ``` puts() ``` are they a perfect solution for string input and output?
getsis marked as obsolescent in C99 and has been removed in C11 because of security issues with this function. Don't use it, usefgetsinstead. As an historical note,getswas exploited (in fingerd) by the first massive internet worm: the inet worm back in 1988. putsfunction is OK if it fits your needs.
Is there any current, relatively simple way to compile and upload full .c/.cpp files for the Arduino DUE on Linux? I'm beginning to regularly run into issues using the boilerplate code they provide around the sketches and so far, there is very little in the way of documentation or alternative IDE support for the ardu...
There is a great examplehere. He explains what you need and how to use it to be able to upload to the due from the terminal of a linux box. He has done a great job in helping you set up an environment to compile and upload your c programs onto the SAM3X8E. He even gives you a makefile and sample code. What more coul...
Do they return the IP header and mac header respectively? I'm a little confused because just looking at the implementation, they are returning pointers that are skb->head + skb->network_header and the like. Why not just get the network header by doing skb->network_header? Thanks!
There are 2 versions ofskb_network_header() ``` #ifdef NET_SKBUFF_DATA_USES_OFFSET static inline unsigned char *skb_network_header(const struct sk_buff ) { return skb->head + skb->network_header; } #else static inline unsigned char *skb_network_header(const struct sk_buff *skb) { return skb->network_hea...
I am getting the following erors: ``` 1. expected = , ; before { (line 2) 2. expected { at end of input (line 12) ``` Here is my code: ``` #include <stdio.h> #include "evenSum.h" int Even_Sum(int array, int i) { for(i = 0; i < 10; ++i) { if(array[i] % 2 =0) { int sum=0; sum ...
Add a;after theint Even_Sum(int array, int i)in your header file. Without that;the compiler sees ``` int Even_Sum(int array, int i) int Even_Sum(int array, int i) { for(i = 0; i < 10; ++i) { ... etc ... ``` This, of course, is not valid c syntax. Therefore, you need the;. Editas others pointed out, you w...
I don't understand how thisprintf()call is working to add together two numbers. Does the%*chave something to do with it? ``` //function that returns the value of adding two number int add(int x, int y) { NSLog(@"%*c",x, '\r'); NSLog(@"%*c",y, '\r'); return printf("%*c%*c", x, '\r', y, '\r'); // need to ...
When passed toprintf(or similar functions),%*cmeans you're passing two parameters instead of one. The first parameter specifies a field width, and the second a character (or string, int, etc.) to write out in that width of field. printfreturns the total number of characters written to the output stream.
This question already has answers here:While-loop ignores scanf the second time(3 answers)Second scanf is not working(5 answers)Closed9 years ago. Program: ``` #include <stdio.h> int main() { char t; while(1) { t='\0'; printf("\nExit?(y/n): "); scanf("%c", &t); if( t=='y' || t...
You need to ensure thatscanfdiscards the newline. Try like this: ``` scanf(" %c", &t); ```
For example,suppose I have something like "0000 0000 0000 1110". How can I access the left most 1 and change it to 0?
This two functions can handle 64 bit value. ``` uint8_t get_bit(uint64_t bits, uint8_t pos) { return (bits >> pos) & 0x01; } uint64_t set_bit(uint64_t bits, uint8_t pos, uint8_t value) { uint64_t mask = 1LL << (63 - pos); if (value) bits |= mask; else bits &= ~mask; return bits; } uint6...
I'm trying my C code to build with autotools on mingw+msys. Could you tell me how to link library likews2_32.libwhen I useautotools. I think I have to editconfigure.acorMakefile.am.
Like this, in the Makefile.am: ``` AM_LDFLAGS = -lws2_32 bin_PROGRAMS = myApp myApp_SOURCES = myApp.c ... ```
I am new to C and have a few basic questions; I read some tutorials and looked at several questions, but I am still a little confused due to some of the wording. ``` #include <stdio.h> int main(int argc, char **argv){ printf("%s",argv[1]); } ``` Lets say I compile and run the file:./test blah blah To my underst...
The value atargv[1][1]has typechar(sinceargvhas typechar **) so you should use the%c(unsigned character) printf format: ``` printf("%c\n", argv[1][0]); // => b printf("%c\n", argv[1][1]); // => l printf("%c\n", argv[1][2]); // => a printf("%c\n", argv[1][3]); // => h ```
I was reading a source code when I saw functions with parentheses in their names: ``` extern int LIB_(strcmp) ( const char* s1, const char* s2 ); extern char LIB_(tolower) ( char c ); ``` What is that? I am confused because I could call the functions like this:char c = LIB_(tolower)('A'); Isn't it true that in C, ...
This is indeed confusing.LIB_(x)is amacrodefined somewhere, which evaluates to the real name of the function. So the function's name is not actuallyLIB_(strcmp)but the result of theLIB_(x)macro. Most likely,LIB_(x)is intended to prepend a library name/identifier onto the beginning of the function and is defined like ...
I having a problem while passing a 2d array to a function. Have a look at the code-: ``` #include<stdio.h> void display(int (*arr)[3],int i,int j,int length,int breadth) { for(;i<length;i++){ for(;j<breadth;j++){ printf("%d ",arr[i][j]); } printf("\n"); } } v...
With what you are doing, when will j get reset to 0?
I am new to C and have a few basic questions; I read some tutorials and looked at several questions, but I am still a little confused due to some of the wording. ``` #include <stdio.h> int main(int argc, char **argv){ printf("%s",argv[1]); } ``` Lets say I compile and run the file:./test blah blah To my underst...
The value atargv[1][1]has typechar(sinceargvhas typechar **) so you should use the%c(unsigned character) printf format: ``` printf("%c\n", argv[1][0]); // => b printf("%c\n", argv[1][1]); // => l printf("%c\n", argv[1][2]); // => a printf("%c\n", argv[1][3]); // => h ```
I was reading a source code when I saw functions with parentheses in their names: ``` extern int LIB_(strcmp) ( const char* s1, const char* s2 ); extern char LIB_(tolower) ( char c ); ``` What is that? I am confused because I could call the functions like this:char c = LIB_(tolower)('A'); Isn't it true that in C, ...
This is indeed confusing.LIB_(x)is amacrodefined somewhere, which evaluates to the real name of the function. So the function's name is not actuallyLIB_(strcmp)but the result of theLIB_(x)macro. Most likely,LIB_(x)is intended to prepend a library name/identifier onto the beginning of the function and is defined like ...
I having a problem while passing a 2d array to a function. Have a look at the code-: ``` #include<stdio.h> void display(int (*arr)[3],int i,int j,int length,int breadth) { for(;i<length;i++){ for(;j<breadth;j++){ printf("%d ",arr[i][j]); } printf("\n"); } } v...
With what you are doing, when will j get reset to 0?
I was reading a source code when I saw functions with parentheses in their names: ``` extern int LIB_(strcmp) ( const char* s1, const char* s2 ); extern char LIB_(tolower) ( char c ); ``` What is that? I am confused because I could call the functions like this:char c = LIB_(tolower)('A'); Isn't it true that in C, ...
This is indeed confusing.LIB_(x)is amacrodefined somewhere, which evaluates to the real name of the function. So the function's name is not actuallyLIB_(strcmp)but the result of theLIB_(x)macro. Most likely,LIB_(x)is intended to prepend a library name/identifier onto the beginning of the function and is defined like ...