question
stringlengths
25
894
answer
stringlengths
4
863
This question already has answers here:Closed10 years ago. Possible Duplicate:C: for loop int initial declaration Can we declare some variables inforstatement in C programming?If so,in which version of c standard will we find the feature?
Yes, you can do that starting with the c99 standard. A straight compile of the code: ``` int main() { for(int i = 0; i<10; i++) printf("%d\n", i); return 0; } ``` with (the default "gnu89")gccwould give you the answer: In functionmain:error: 'for' loop initial declarations are only allowed in C99 modenot...
I would like to take an array of strings in a macro. Firstly: is that possible? IF yes, can I call them one by one based on the index, when I am using them? Something like this: ``` #define VAR "abc", "def", "xyz" ``` Then when i want to use "def" somewhere, ``` FUNC(VAR[1]); ```
May be my code helpful to you: ``` #include<stdio.h> #include<stdlib.h> #define STRING_ARRAY "ONE", "TWO", "THREE", "NULL" int main(){ char* STRING[] = {STRING_ARRAY}; int i=0; scanf("%d",&i); printf("%s\n",STRING[i]); return EXIT_SUCCESS; } ``` This also works: ``` :~$ gcc x.c -o x :~$ ./...
If I don't care about the return status of my thread, would I need to have a pthread_exit? I'm wondering if there might be some subtle resource problems associated with not calling pthread_exit in my datached pthreads. Thanks.
The purposepthread_exit()is to return the exit code if any other threads thatjoins. From themanual: ``` Performing a return from the start function of any thread other than the main thread results in an implicit call to pthread_exit(), using the function's return value as the thread's exit status. ``` So, it ...
I have the following code: ``` #include<stdio.h> #include<stdlib.h> #define MACRO_TEST(MESSAGE,args...) { \ const char *A[] = {MESSAGE}; \ printf("this is a test\n");\ if(sizeof(A) > 0) \ printf(*A,##args); \ } int main () { MACRO_TEST(); MACRO_TEST("hello %d\n",5); return 0; } ``` And when I ...
It's complaining about this line ``` printf(*A,##args); ``` Change it to ``` printf(""MESSAGE, ##args); ```
This question already has answers here:Closed10 years ago. Possible Duplicate:C/C++ line number I want to display the line number where the printf is triggered? It may look like this: ``` printf("the line number is: %d",SOME_LIBC_MACRO); ``` How to do it?
Use the__LINE__macro ``` printf("the line number is: %d", __LINE__); ``` Lists of other pre-defined macros are available forGCCandVisual Studio
This question already has answers here:Closed10 years ago. Possible Duplicate:How to find the size of a variable with out using sizeof using C, can we somehow find the size of a pointer without using sizeof operator ? though i found this question at lot of places while googling, but i couldn't find any answer. any h...
Here is a small but legal hack that you can use: ``` int *unused = NULL; int **ptr = &unused; printf("%tu\n", ((char*)(ptr+1))-(char*)ptr); ``` Here is how it works: Recall that addingNto a pointer addsNtimes the size of the type pointed to; hence(ptr+1)addssizeof(int*)to the "raw" value ofptrsizeof(char)is always1...
I'm writing to message queue ``` if (msgsnd(q, &msg, sizeof(message), slaves_list[to]) == -1) ``` and reading ``` if (msgrcv(q, &msg, sizeof(message), id, 0) == -1) ``` but what if this queue is empty? How to check that? If there is nothing I want execute next instruction in the loop
UseIPC_NOWAIT. From thedocumentation: If(msgflg & IPC_NOWAIT)is non-zero, the calling thread will return immediately with a return value of-1and errno set to[ENOMSG].
I printed sizeof(struct tm) in C using sizeof() operator it gives me 44 bytes.But in man page of ctime it has 9 int variables for time.then its size should be 36. How it is giving 44?
http://linux.die.net/man/3/ctime The glibc version of struct tm has additional fieldslong tm_gmtoff; /* Seconds east of UTC */ const char *tm_zone; /* Timezone abbreviation */ That's where you extra bytes come from (probably).
This question already has answers here:Closed10 years ago. Possible Duplicate:C - initialization of pointers, asterisk position What is the difference between these declarations: ``` char* str; ``` and ``` char *str; ``` Is there a difference at all? Another example: ``` char* str; struct StrStackLink *nex...
There is no difference - both declare a pointer to a char. There is a difference when you declare multiple variables on the same line however ``` char* str1, str2; ``` declaresstr1to be a pointer andstr2to be a char, while ``` char *str1, *str2; ``` declares two char pointers
I'm currently building a small virtual machine in c modelling an old 16-bit CPU, which runs at a super slow clock speed (a few 100 Khz). How would I throttle the virtual machine's processing speed of opcode, etc..? or would I even want to?
As I said in the comments I suggest using some sort of timer mechanism if you would like to match a certain speed here is how I would do it: ``` 1 kHz 1000 Hz 1/s ----- * ------- * ----- therefore 1 kHz = 1000/s 1 1 kHz 1 Hz ``` which means every second 1000 operations are occurring, s...
This may sound very silly and stupid.I am tyring to understand the difference between ``` char *token[32]; ``` and ``` char token[32]; ``` char token[32] declares token to be character array that can contain 32 characters. In case of char *token[32],token holds 32 character pointers.What does these pointers point...
Nowchar *token[32]declares token to be a pointer to character array that can contain 32 characters. No. It declarestokento be an array of 32 char pointers. In other words, in the first casetokenholds 32 characters, in the second case, it holds 32 pointers. If you wanted to declare a pointer to a character array that...
I want to be able to merge multiple midi files and wav files and produce single wav or mp3 file in Python or C. Is there a library that does this? Do I have to first convert MIDI to wav and then merge wav files together? I know there are libraries out there for Python that does that, but I didn't know if there's a way...
You're mixing audio apples and oranges here. :) WAV files are sampled audio, whereas MIDIs are only instructions that tell a MIDI player what to play and with which instruments. You can't directly mix WAVs and MIDIs, but if you render the MIDI sequence to a WAV, then you can mix stuff however you like. TiMidity++ i...
I am trying to figure out the best way to write a cross platform kernel code/shell script to list all the kernel task{(pid/tid , name)}in alinuxdis. machine. it should be the most general possible. I tried to useps -Tbut it is seems to be inaccurate and some platform don't support it in theirbusybox. Any suggestions?
If you want to distinguish user processes from kernel tasks, then this is a previous discussion on the subject:Identifying kernel threads My answer to that question does not require any tools, it simply reads the contents of /proc//stat, so it should work on any distribution.
Since inC\C++\Java- int 2a ; //invalid suffix "a" on integer constant Is there nothing wrong with digits in the rest of variant name although it's valid syntax ? Like - ``` int num1 ; int num_1st ; int num_2nd ; ```
I've never heard of anybody (e.g., any coding standards/guidelines) that had a problem with digits in an identifier. Nonetheless, too many of themcanindicate that a vector or array might be preferable -- even with only two, yournum_1standnum_2ndmight be better asnumbers[2].
I want to define a macro function which support at the same time: 1) No input parameter 2) Input parameters some thing like that: ``` #define MACRO_TEST(X)\ printf("this is a test\n");\ printf("%d\n",x) // the last printf should not executed if there is no input parameter when calling the macro ``` In the...
You can use sizeof for this purpose. Consider something like this: ``` #define MACRO_TEST(X) { \ int args[] = {X}; \ printf("this is a test\n");\ if(sizeof(args) > 0) \ printf("%d\n",*args); \ } ```
I want to add the ascii values of a string, say "hello". What is the best way to do that in c? is There a way without looping the string?
Of course, you can do it without looping: ``` #include <stdio.h> int sum(const char *s) { return *s == 0 ? 0 : *s + sum(s + 1); } int main() { printf("%d\n", sum("hello")); return 0; } ```
This question already has answers here:Closed10 years ago. Possible Duplicate:C/C++ line number I want to display the line number where the printf is triggered? It may look like this: ``` printf("the line number is: %d",SOME_LIBC_MACRO); ``` How to do it?
Use the__LINE__macro ``` printf("the line number is: %d", __LINE__); ``` Lists of other pre-defined macros are available forGCCandVisual Studio
This question already has answers here:Closed10 years ago. Possible Duplicate:How to find the size of a variable with out using sizeof using C, can we somehow find the size of a pointer without using sizeof operator ? though i found this question at lot of places while googling, but i couldn't find any answer. any h...
Here is a small but legal hack that you can use: ``` int *unused = NULL; int **ptr = &unused; printf("%tu\n", ((char*)(ptr+1))-(char*)ptr); ``` Here is how it works: Recall that addingNto a pointer addsNtimes the size of the type pointed to; hence(ptr+1)addssizeof(int*)to the "raw" value ofptrsizeof(char)is always1...
I'm writing to message queue ``` if (msgsnd(q, &msg, sizeof(message), slaves_list[to]) == -1) ``` and reading ``` if (msgrcv(q, &msg, sizeof(message), id, 0) == -1) ``` but what if this queue is empty? How to check that? If there is nothing I want execute next instruction in the loop
UseIPC_NOWAIT. From thedocumentation: If(msgflg & IPC_NOWAIT)is non-zero, the calling thread will return immediately with a return value of-1and errno set to[ENOMSG].
I printed sizeof(struct tm) in C using sizeof() operator it gives me 44 bytes.But in man page of ctime it has 9 int variables for time.then its size should be 36. How it is giving 44?
http://linux.die.net/man/3/ctime The glibc version of struct tm has additional fieldslong tm_gmtoff; /* Seconds east of UTC */ const char *tm_zone; /* Timezone abbreviation */ That's where you extra bytes come from (probably).
This question already has answers here:Closed10 years ago. Possible Duplicate:C - initialization of pointers, asterisk position What is the difference between these declarations: ``` char* str; ``` and ``` char *str; ``` Is there a difference at all? Another example: ``` char* str; struct StrStackLink *nex...
There is no difference - both declare a pointer to a char. There is a difference when you declare multiple variables on the same line however ``` char* str1, str2; ``` declaresstr1to be a pointer andstr2to be a char, while ``` char *str1, *str2; ``` declares two char pointers
I'm currently building a small virtual machine in c modelling an old 16-bit CPU, which runs at a super slow clock speed (a few 100 Khz). How would I throttle the virtual machine's processing speed of opcode, etc..? or would I even want to?
As I said in the comments I suggest using some sort of timer mechanism if you would like to match a certain speed here is how I would do it: ``` 1 kHz 1000 Hz 1/s ----- * ------- * ----- therefore 1 kHz = 1000/s 1 1 kHz 1 Hz ``` which means every second 1000 operations are occurring, s...
I'd like to kill a thread from another thread and I'd like to do when it is running, so it won't be anything like change the loop variable to something. What would be the most appropriate way to do it? To be more clear, I am using cURL and after some point i don't want curl to perform downloading. curl API does not p...
Killing a thread is rarely a good idea because it can very easily lead to memory/resource leaks. A killed thread only cleans up it's stack and the memory used by the thread itself, nothing allocated via new/malloc etc. However, if you really want to kill the thread, with pthreads the correct way to do it is to callpt...
Does the Android NDK expose the values generated by the sensors in pre-defined portions of memory so i can do something like this ``` T* ptr = 0x124 ``` ? It's this possible and it's this being standardized by the Android team ?
No. And it's pretty inconceivable that they would do this. The NDK keeps you much more isolated from the hardware than even a typical C-on-unix environment would, both mandatorily due to the security model, and also advisably due to the major variability of these details between the numerous Android versions and ven...
I have the following codes: ``` const int N=3; static double * p[N]; ``` Does p stands for a static pointer pointing to a N-dimensional double array, or a N-dimensional array with each elements standing for a static pointer? Also I found the following change failed compilation, and not sure why... ``` int N=3; sta...
Does p stands for a static pointer pointing to a N-dimensional double array, or a N-dimensional array with each elements standing for a static pointer? Almost the second choicea N-sized array with each elements standing for a static pointer. Note the change from "N-dimensional" to "N-sized". Thanks @David. Also I fo...
Is there any difference between ``` static int * pn; ``` and ``` int static * pn; ``` Basically I am looking for difference between a pointer pointing to a static variable, and a static pointer pointing to some variable, and not sure whether the above 2 declarations corresponds to them.
In C there is no difference but the second form is discouraged. (C99, 6.11.5p1) "The placement of a storage-class specifier other than at the beginning of the declaration specifiers in a declaration is an obsolescent feature"
I've been trying to learn about the different data structures used in popular languages that I have experience with such as lists and dictionaries in Python, associative arrays in PHP (essentially hash tables), vectors in C++, etc. I have a lot of colleagues that use R religiously and I was wondering how vectors, mat...
As already mentioned, check out the"R internals"manual, as well asthis part of "Writing R extensions".
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. I want to extract ACPI tables in C#...
You may start with thePlatform Invoke Tutorial.
Creating header guards for my h/hpp files has always been standard practice for me, but I wonder, why is it even possible to include de same file twice? Is there a case where you actually need unprotected headers?
"Parameterized" header files can be used to simulate C++-ish-style templates in C. In such cases the header file will depend on a number of macros ("template parameters"). It will generate different code depending on the actual "value" of these macros. So, the typical usage of such header would look as a sequence of ...
This question already has answers here:Closed10 years ago. Possible Duplicate:C preprocessor and concatenation I have the macro ``` #define BUS B ``` I want to make macroBUS_PORTthat expands toPORTB. I did following: ``` #define BUS_PORT PORT ## BUS ``` ButBUS_PORTexpands toPORTBUS. What I did wrong? How to mak...
As explained inthis answer, you need an extra level of indirection. E.g. ``` #define BUS B #define PASTER(x,y) x ## y #define EVALUATOR(x,y) PASTER(x,y) #define BUS_PORT EVALUATOR(PORT, BUS) ```
though there are already several questions asked on this forum & others related to sizeof operator, i could not get any answer on how compiler evaluates the sizeof operator to find the size of any datatype, variable, pointer,array etc. if possible also point me to some links which can help me understand this in detail...
The compiler justknowsthe size of primitive datatypes; this knowledge is fundamentally built in to the compiler. For traditional fixed-size arrays and complex data types (structs and classes), it just adds up the sizes of the constituent primitives and accounts for any necessary padding. Seehttp://en.wikipedia.org/wi...
I'm usingFFMPegon my iPhone project, but I'm getting a warning when usingAVFrame *pFrame, like this: ``` AVFrame *pFrame uint8_t *data[AV_NUM_DATA_POINTERS]; ... pFrame->data ``` This is the warning I'm getting: ``` Passing 'uint8_t *[8]' to parameter of type 'const uint8_t *const *' (aka 'const unsigned char *c...
Cast it to the type the function is expecting: (const uint8_t *const *)(pFrame->data)
Porting some legacy C code from QNX (Photon C compiler) to Linux (GCC). In several places I see code like this: ``` void process_data(char key, char *data) { int i; /* Required for compilation */ i=i; key=key; data=data; ... } ``` Obviously this code is NOT required for compilation and it d...
This removes compilation warnings/errors about unreferenced variables. Usually such stuff is done either by#pragmas or by a more expressive form, such as macro:#define unused_var(x) (x)=(x)
I'm trying to make some project in C. I would like to know if it is possible to make#includefrom the same file twice, in a way that recalls diamond heritage. i.e. ina.cthere is#include "a.h"inb.cthere is#include "b.h"inb.hthere is#include "a.h" Is it possible to#include "b.h"ina.c? I get an error: ``` some_varia...
Simple: don'tdefinevariables in headers, justdeclarethem: Header: ``` // a.h #ifndef A_H // always use #include guards #define A_H extern int my_variable; // declare my_variable ... #endif ``` Source file a.c: ``` // a.c #include "a.h" int my_variable; // define my_variable ... ``` Sourc...
If the fork and exec patter is used just to run a program without freeze the current program, what's the advantage, for example, over using this single line: ``` system("program &"); // run in background, don't freeze ```
Thesystemfunction creates a new shell instance for running the program, which is why you can run it in the background. The main difference fromfork/execis that usingsystemlike this actually creates two processes, the shell and the program, and that you can't communicate directly with the new program via anonymous pip...
I'd like to kill a thread from another thread and I'd like to do when it is running, so it won't be anything like change the loop variable to something. What would be the most appropriate way to do it? To be more clear, I am using cURL and after some point i don't want curl to perform downloading. curl API does not p...
Killing a thread is rarely a good idea because it can very easily lead to memory/resource leaks. A killed thread only cleans up it's stack and the memory used by the thread itself, nothing allocated via new/malloc etc. However, if you really want to kill the thread, with pthreads the correct way to do it is to callpt...
Does the Android NDK expose the values generated by the sensors in pre-defined portions of memory so i can do something like this ``` T* ptr = 0x124 ``` ? It's this possible and it's this being standardized by the Android team ?
No. And it's pretty inconceivable that they would do this. The NDK keeps you much more isolated from the hardware than even a typical C-on-unix environment would, both mandatorily due to the security model, and also advisably due to the major variability of these details between the numerous Android versions and ven...
I have the following codes: ``` const int N=3; static double * p[N]; ``` Does p stands for a static pointer pointing to a N-dimensional double array, or a N-dimensional array with each elements standing for a static pointer? Also I found the following change failed compilation, and not sure why... ``` int N=3; sta...
Does p stands for a static pointer pointing to a N-dimensional double array, or a N-dimensional array with each elements standing for a static pointer? Almost the second choicea N-sized array with each elements standing for a static pointer. Note the change from "N-dimensional" to "N-sized". Thanks @David. Also I fo...
Is there any difference between ``` static int * pn; ``` and ``` int static * pn; ``` Basically I am looking for difference between a pointer pointing to a static variable, and a static pointer pointing to some variable, and not sure whether the above 2 declarations corresponds to them.
In C there is no difference but the second form is discouraged. (C99, 6.11.5p1) "The placement of a storage-class specifier other than at the beginning of the declaration specifiers in a declaration is an obsolescent feature"
I've been trying to learn about the different data structures used in popular languages that I have experience with such as lists and dictionaries in Python, associative arrays in PHP (essentially hash tables), vectors in C++, etc. I have a lot of colleagues that use R religiously and I was wondering how vectors, mat...
As already mentioned, check out the"R internals"manual, as well asthis part of "Writing R extensions".
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. I want to extract ACPI tables in C#...
You may start with thePlatform Invoke Tutorial.
Creating header guards for my h/hpp files has always been standard practice for me, but I wonder, why is it even possible to include de same file twice? Is there a case where you actually need unprotected headers?
"Parameterized" header files can be used to simulate C++-ish-style templates in C. In such cases the header file will depend on a number of macros ("template parameters"). It will generate different code depending on the actual "value" of these macros. So, the typical usage of such header would look as a sequence of ...
This question already has answers here:Closed10 years ago. Possible Duplicate:C preprocessor and concatenation I have the macro ``` #define BUS B ``` I want to make macroBUS_PORTthat expands toPORTB. I did following: ``` #define BUS_PORT PORT ## BUS ``` ButBUS_PORTexpands toPORTBUS. What I did wrong? How to mak...
As explained inthis answer, you need an extra level of indirection. E.g. ``` #define BUS B #define PASTER(x,y) x ## y #define EVALUATOR(x,y) PASTER(x,y) #define BUS_PORT EVALUATOR(PORT, BUS) ```
though there are already several questions asked on this forum & others related to sizeof operator, i could not get any answer on how compiler evaluates the sizeof operator to find the size of any datatype, variable, pointer,array etc. if possible also point me to some links which can help me understand this in detail...
The compiler justknowsthe size of primitive datatypes; this knowledge is fundamentally built in to the compiler. For traditional fixed-size arrays and complex data types (structs and classes), it just adds up the sizes of the constituent primitives and accounts for any necessary padding. Seehttp://en.wikipedia.org/wi...
I'm usingFFMPegon my iPhone project, but I'm getting a warning when usingAVFrame *pFrame, like this: ``` AVFrame *pFrame uint8_t *data[AV_NUM_DATA_POINTERS]; ... pFrame->data ``` This is the warning I'm getting: ``` Passing 'uint8_t *[8]' to parameter of type 'const uint8_t *const *' (aka 'const unsigned char *c...
Cast it to the type the function is expecting: (const uint8_t *const *)(pFrame->data)
Porting some legacy C code from QNX (Photon C compiler) to Linux (GCC). In several places I see code like this: ``` void process_data(char key, char *data) { int i; /* Required for compilation */ i=i; key=key; data=data; ... } ``` Obviously this code is NOT required for compilation and it d...
This removes compilation warnings/errors about unreferenced variables. Usually such stuff is done either by#pragmas or by a more expressive form, such as macro:#define unused_var(x) (x)=(x)
I'm trying to make some project in C. I would like to know if it is possible to make#includefrom the same file twice, in a way that recalls diamond heritage. i.e. ina.cthere is#include "a.h"inb.cthere is#include "b.h"inb.hthere is#include "a.h" Is it possible to#include "b.h"ina.c? I get an error: ``` some_varia...
Simple: don'tdefinevariables in headers, justdeclarethem: Header: ``` // a.h #ifndef A_H // always use #include guards #define A_H extern int my_variable; // declare my_variable ... #endif ``` Source file a.c: ``` // a.c #include "a.h" int my_variable; // define my_variable ... ``` Sourc...
If the fork and exec patter is used just to run a program without freeze the current program, what's the advantage, for example, over using this single line: ``` system("program &"); // run in background, don't freeze ```
Thesystemfunction creates a new shell instance for running the program, which is why you can run it in the background. The main difference fromfork/execis that usingsystemlike this actually creates two processes, the shell and the program, and that you can't communicate directly with the new program via anonymous pip...
I have a question regarding the saving of characters in C char arrays. I must read text from a file into a array of type "char" (i cannot use unsigned char). When there are certain characters with a value over 127 (e.g. €, ä, ö, ...) it saves them as negative values, but they do often take more space (e.g. € takes 3 ...
I think you should read this:http://www.joelonsoftware.com/articles/Unicode.html
I'm a beginner in C. Is there any datatype for dates?In C we have for working with time, is there one for dates too?How can I calculate difference between two dates?
Yes,the standard libraryC Time Librarycontains structures and functions you want.You can usestruct tmto store date anddifftimeto get the difference.
I have a data structure: ``` typedef struct{ int a; int b; int c; }EVENTS; EVENTS newone[20]; ``` Then I use newone somewhere. Now, I want to reset all values of newone[20] to 0. Is there a short way to do this? Thanks
The shortest way is to usememset ``` memset(newone, 0, sizeof(newone)); ```
We want to ensure that upto 10 decimal point values are kept while converting a double value to a string. When we tried %e or %f, it will not keep more than 5 decimal points. When we tried %.14f, the small values (less than 1.0e-20) are not properly converted to string. What format string to be used to keep upto 1...
Try%.17gto print with the most appropriate format for the double in question. ``` printf("%.17g\n", 10000.); printf("%.17g\n", 240.0008); printf("%.17g\n", 0.0000000013); 10000 240.0008 1.3000000000000001e-009 ```
When I write: ``` int a; int c; ``` OR ``` int a, c; ``` When areaandcstored inadjacentplaces in the memory? ((&a+1)equals&c?)Does the way you define them has influence on this? Or it only depends on the machine?
No, you cannot guarantee thataandcare in adjacent places in memory, but that is usually the case. I believeusually&a - 1will be equal to&cas the stackusuallygrows downwards. If you want contiguous variables then use an array. Does the way you define them has influence on this? Usually the compiler won't reorder unl...
I'm usinggnu cppfor some tests and hope it preserves the#includemacro and extends other user-defined macro meanwhile. Is it possible? Here's a piece of code(foo.c): ``` #include <stdio.h> #define NEWLINE(str) str "\n" int main(){ puts(NEWLINE("foo")); } ``` And I hope the result ofcpp foo.cto be: ``` #include <st...
You could use a script to comment out every #include, run cpp and then remove these comments.
I want to send data sensors to server using udp client server. ``` printf("sensor 0 '%s' \n",buf0); printf("sensor 1 '%s' \n",buf1); ``` for example the value of the buf0 is 1023 and value of buf1 is 0. I want to merge sensor 0 :1023 in a buffer say buff so I can send buff to the server. and server will receive ...
You can usesnprintf ``` snprintf(buf, 100, "sensor 0 : %s", buf0); ``` where buf is of typechar buf[100];
The messages are below: ``` $:~/software/version_1.02/example$ gcc -Wall -Wextra example.c -I../include -L../lib -lnnmf -larpack -llapack \ -lblas -o main In file included from example.c:47: ../include/nmfdriver.h:92:7: warning: no newline at end of file example.c:53: warning: unused parameter ‘argc’ example.c:53: wa...
It might be looking for the libraries without the version suffixes.Try making a link without a version suffix to one of the versioned ones: ``` sudo ln -s /usr/lib/arpack.so.2 /usr/lib/arpack.so ```
I recently use MPICH2 to write parallel code. But when I runwmpiexec.exeinbin\I received this: Please specify an authentication passphrase for smpd: what is going on here?
I was also facing this same issue, but simply wmpiregister.exe does not work. So I followed the following steps and it worked: 1- Disable your Firewall (or modify the rules) 2- Open an admin command prompt by right-clicking on the command prompt icon selecting run as administrator. 3- Type the following commands o...
This question already has answers here:Closed10 years ago. Possible Duplicate:C preprocessor and concatenation Is it possible to concatenate aCpreprocessor with a variable name? ``` #define WIDTH 32 int dataWIDTH; // dataWIDTH should be interpreted as 'data32' printf("%d",dataWIDTH); ```
Your use case requires a double-unescaping; using the token pasting (##) operator by itself will just append the name of the preprocessor directive. ``` #define WIDTH 32 #define _MAKEDATA(n) data##n #define MAKEDATA(n) _MAKEDATA(n) int MAKEDATA(WIDTH) = 7; int _MAKEDATA(WIDTH) = 8; int main(int argc, char *argv[])...
I am trying to frame the ICMP packet and send it through raw socket. Looking at the examples, I see that the IP packet length is calculated as : iphdr.ip_hl = sizeof(struct ip) >> 2 Can you please explain why we need to right shift struct ip by 2 times instead of assigning a constan value ?
The 'ip_hl' field of an IP (or ICMP) packet is defined as the length of the IP header, in 32-bit words. sizeof(struct ip) yields the length of the IP header, in 8-bit bytes. Right shifting this value twice provides the length in 32-bit words, as expected in the ip_hl field. A good reason not to use a constant for t...
I have tried googling this but all I get is results on how to compile a basic program. Is it possible to compile code to a specific C++ standard using Clang++ and G++ by specifying that code should be compiled to say, C89, C99, C++98, etc?
You can use the -std flag. For example, to compile to C99, use-std=c99 The documentation for it ishere
I'm just trying to pass copywords from the function get_string in to fileinput in main. the compiler says error in function get_string while referencing line 5 which is the first line of main. ``` #include <stdio.h> #include <stdlib.h> char get_string (char * copywords[100]) int main (){ char fileinput[100]; get_st...
You're missing a semicolon in the prototype forget_string(), right beforemain(). ``` char get_string (char * copywords[100]); ^ | IMPORTANT ``` This causes the function definitions to nest, which is not a...
I am writing an open-source tool for run-time memory issue debugging: https://github.com/sandeepsinghmails/S_malloc The current version requires the user to change his/her wrapper functions formalloc()andfree()and call two additional functions from my library. I want to modify this code so that the user'smalloc()an...
Take a look at malloc_hooks: http://man7.org/linux/man-pages/man3/malloc_hook.3.html The GNU C library lets you modify the behavior of malloc(3), realloc(3), and free(3) by specifying appropriate hook functions. You can use these hooks to help you debug programs that use dynamic memory allocation, for...
So here is my attempt at it but I'm getting a few errors which I don't know how to fix. 17.2 Warning : passing argument 2 of putc makes pointer from integer without a cast. C:\mingw ....... note expected Struct FILE* but' but argument is of type int. ``` #include <stdio.h> #include <stdlib.h> int main (void) { ...
Second argument toputcis a file stream. But you pass a plain charcter. Use: ``` while(c != EOF) { putc(c, stdout); c = getc(fp); } ``` to print in stdout.
I need to write a SFTP server in C for a HP NonStop (Tandem). There's an existing FTP server using functions such asFTPopen(),FTPput()andFTPclose(). Where can I find documentation on these functions? As usual with HP NonStop documentation, Google is of little use...
See the HP NonStop TCP/IP Applications and Utilities User Guide Chapter 8 is titled "FTP API External Specification". Information about the regular FTP server API is in there. Note: If you have a recent version of Guardian on Itanium or Blade servers then it will either already come with HP NonStop SSH or you can b...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. Does memory allocation for pointer ...
In the first case the pointer is initialized to point to address 0, so if you access the data the pointer points to, you get a 0-pointer exception, because the pointer does not point to a accessible memory-location. In the second case, p=(struct_datatype *)malloc (sizeof (struct_datatype)); memory is allocated and as...
I just noticed that there has been a correction to the C11 standard calledISO/IEC 9899:2011/Cor 1:2012. What was changed in this update?
This technical corrigendum is available free of charge, fromISOor from your national standard institute. For convenience, I will cite it as whole here, since there are just two changes: Page 176, 6.10.8.1Replace:__STDC_VERSION__The integer constant201ymmL.178)with:__STDC_VERSION__The integer constant201112L.178)Page...
Is there a way to force sscanf to NOT allow extra whitespace. Following code accepts"N_ 234", even though it should only accept"N_234": ``` int r; unsigned b; r = sscanf("N_ 234", "N_%u", &b); /* Returns 1 */ ``` Tested with IAR compiler.
Try this: ``` int r; unsigned b; char c[20]; r = sscanf("N_ 234", "N_%[0-9]", c); /* Returns 0 */ r = sscanf("N_-234", "N_%[0-9]", c); /* Returns 0 */ r = sscanf("N_1234", "N_%[0-9]", c); /* Returns 1 */ b = atoi(c); ```
I need to encode all occurrence of<character in a C/C++ code file. To prevent conflict, I need to know which characters are not reserved in C/C++ standard. For example, if$is not reserved, I can encode<to$temporarily and revive the original C/C++ code later. I need this encoding for my C/C++ code in the XML-like inte...
Rather than list unreserved characters (there are infinite), here are the reserved ones from 2.3.1 of the standard: ``` space, horizontal tab, vertical tab, form feed, new line a through z A through Z 0 through 9 _ { } [ ] # ( ) % : ; . ? * + - / ^ & | ~ ! = , \ " ' ```
I know the meaning of this statement ``` scanf("%d",&x); ``` But what does this statement do ``` scanf("%2d",&x); ``` I tried searching for this, but could not find an answer. I want to know what happens internally also.
That's two digits number: ``` int n = 0; scanf ("%2d", &n); printf ("-> %d\n", n); ``` 12 -> 12 88657 -> 88
This question already has an answer here:Closed10 years ago. Possible Duplicate:What is the rationale in allowing `?` to be escaped? If I can do this: ``` string i = "'"; ``` Why do this: ``` string i = "\'"; ```
You need it if you want a character literal: ``` char apos = '\''; ```
For the following code: ``` int (*ptr)[10]; int a[10]={99,1,2,3,4,5,6,7,8,9}; ptr=&a; printf("%d",(*ptr)[1]); ``` What should it print? I'm expecting the garbage value here but the output is1.(for which I'm concluding that initializing this way pointer array i.eptr[10]would start pointing to elements ofa...
int *ptr[10]; This is an array of 10int*pointers, not as you would assume, a pointer to an array of 10ints int (*ptr)[10]; This is a pointer to an array of 10int It is I believe the same asint *ptr;in that both can point to an array, but the given form can ONLY point to an array of 10ints
``` function A(int a[]) { SemLock() //Some Code.... SemUnlock() } ``` Suppose some other thread has taken the same lock. Hence this function is blocked. Suppose this function is called by many other threads. All will be blocked. After Unlocking, will the data (parameter a[]) be lost or retained passed in as the ...
parametera[]is thread specific (non-shareable) so each thread has their own copy ofa[]. When a thread created a data-structure for thread is created.a[]is stored in thread's stack. There is a queue of thread associated with each semaphore variable. ``` typedef struct { int count; queue q; /* queue of threads waitin...
I have a device that runs with Arm(Risc) CPU and I like to write program for it. Transferring binary to this device is easy but I cannot simply put com/exe files compiled in windows in this device. I don't have a clue how can I compile a program to generate an Risc processor bin file (byte order, stack and memory arc...
You might like to look atGNU Armwebsite. It has binaries for compiling for ARM processor in Windows platform. However as Matteo explained in comments, you will need a tool to changeELF formatto Raw format that you desire.
Is there a way to force sscanf to NOT allow extra whitespace. Following code accepts"N_ 234", even though it should only accept"N_234": ``` int r; unsigned b; r = sscanf("N_ 234", "N_%u", &b); /* Returns 1 */ ``` Tested with IAR compiler.
Try this: ``` int r; unsigned b; char c[20]; r = sscanf("N_ 234", "N_%[0-9]", c); /* Returns 0 */ r = sscanf("N_-234", "N_%[0-9]", c); /* Returns 0 */ r = sscanf("N_1234", "N_%[0-9]", c); /* Returns 1 */ b = atoi(c); ```
I need to encode all occurrence of<character in a C/C++ code file. To prevent conflict, I need to know which characters are not reserved in C/C++ standard. For example, if$is not reserved, I can encode<to$temporarily and revive the original C/C++ code later. I need this encoding for my C/C++ code in the XML-like inte...
Rather than list unreserved characters (there are infinite), here are the reserved ones from 2.3.1 of the standard: ``` space, horizontal tab, vertical tab, form feed, new line a through z A through Z 0 through 9 _ { } [ ] # ( ) % : ; . ? * + - / ^ & | ~ ! = , \ " ' ```
I know the meaning of this statement ``` scanf("%d",&x); ``` But what does this statement do ``` scanf("%2d",&x); ``` I tried searching for this, but could not find an answer. I want to know what happens internally also.
That's two digits number: ``` int n = 0; scanf ("%2d", &n); printf ("-> %d\n", n); ``` 12 -> 12 88657 -> 88
This question already has an answer here:Closed10 years ago. Possible Duplicate:What is the rationale in allowing `?` to be escaped? If I can do this: ``` string i = "'"; ``` Why do this: ``` string i = "\'"; ```
You need it if you want a character literal: ``` char apos = '\''; ```
For the following code: ``` int (*ptr)[10]; int a[10]={99,1,2,3,4,5,6,7,8,9}; ptr=&a; printf("%d",(*ptr)[1]); ``` What should it print? I'm expecting the garbage value here but the output is1.(for which I'm concluding that initializing this way pointer array i.eptr[10]would start pointing to elements ofa...
int *ptr[10]; This is an array of 10int*pointers, not as you would assume, a pointer to an array of 10ints int (*ptr)[10]; This is a pointer to an array of 10int It is I believe the same asint *ptr;in that both can point to an array, but the given form can ONLY point to an array of 10ints
``` function A(int a[]) { SemLock() //Some Code.... SemUnlock() } ``` Suppose some other thread has taken the same lock. Hence this function is blocked. Suppose this function is called by many other threads. All will be blocked. After Unlocking, will the data (parameter a[]) be lost or retained passed in as the ...
parametera[]is thread specific (non-shareable) so each thread has their own copy ofa[]. When a thread created a data-structure for thread is created.a[]is stored in thread's stack. There is a queue of thread associated with each semaphore variable. ``` typedef struct { int count; queue q; /* queue of threads waitin...
I have a device that runs with Arm(Risc) CPU and I like to write program for it. Transferring binary to this device is easy but I cannot simply put com/exe files compiled in windows in this device. I don't have a clue how can I compile a program to generate an Risc processor bin file (byte order, stack and memory arc...
You might like to look atGNU Armwebsite. It has binaries for compiling for ARM processor in Windows platform. However as Matteo explained in comments, you will need a tool to changeELF formatto Raw format that you desire.
I have the following code in a global header, so I can make decisions at compile time: ``` enum { MyStyleA, MyStyleB, MyStyleC }; #define STYLE MyStyleB ``` In various source files, I include this header and do something like this: ``` #if STYLE == MyStyleC doSomething(); #endif ``` Problem is,doS...
I don't have a copy of the C standards on my bedside table, so I could be wrong, but: The preprocessor has no idea whatMyStyleCis - that doesn't get a value until it hits the compiler. Compilers normally have an option (used to be -e ?) to output the results of the preprocessor phase (as text) - I'd look at that and...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. i came across a struct in "linux/li...
Yes, a linked list without data elements seems strange. But, did you try searching for usages of the struct in other headers? I am guessing they will use this struct in other structures which need a linked list, like say the buffer free list etc. You will find the data elements there.
This is my UI: This is tab created programmatically: ``` ui->tabWidget->addTab(new QWidget(), "Tab 2"); ``` I want the newly created tab to have the exact same layout as the "Chat room" tab has. Any advice on how to do this would be great.
The easiest way to do this (in Designer) is to create a new UI Form Class called something likeChatTaband base it onQWidget. Move (i.e., cut and paste) your chat room widgets and layout from your MainWindow UI form to the ChatTab form, but leave theQTabWidgetcontainer in your MainWindow form. If you want a chat room ...
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen...
When you expand your macro you get: ``` (*(int *)(&a)) = 20 ``` Forget the(int *)and you get ``` (*(&a)) = 20 ``` Which is equal to: ``` a = 20; ``` Hence you are changing the value ofa!
I know that: ``` char * pword; ``` declares a table which first element is used as a pointer.And ``` *pword <=> * (&pword[0]) <=> pword[0] ``` (Tell me if I'm wrong.) But what I want to know is ifchar*is a type (asintis for integers) and if yes does it represents an address?
Yes,char*is a type, and a variable of that type represents a memory address for achar-type variable (formally a "pointer to char"). TheC data typesarticle on Wikipedia is a good introduction of the various types.
This question already has answers here:Closed10 years ago. Possible Duplicate:How can I allocate a 2D array using double pointers? I used VB 2012 Express to make a maze program. It works really well even when I setROW*COLUMNto499*499, (the maze is an array:unsigned char maze[ROW][COLUMN]). But one time I tried to ...
You are allocatingmazeon the stack, and stack size is typically limited to between 1 and 8 megabytes. To overcome this limitation, allocatemazeon the heap. For suggestions on how to do this, seeHow can I allocate a 2D array using double pointers?andHeap allocate a 2D array (not array of pointers)
Today I came across POSIX thread attributes, they are a little weird work with, when you are using them for the first time. I am a little confused aboutpthread_attr_setdetachstate, which states that: POSIX threads are in Join state (with the thread which created it) by default but in order to join them, we have to ex...
No, you even shouldn't do that: Attempting to detach an already detached thread results in unspecified behavior. So really do either one of them but not both. If you know from the start that you wouldn't joint the thread, use the variant with the attribute. Depending on your system this might save up some time and...
OK, what I'm trying to do may sound a bit complicated, but I still cannot figure it out : Let's say we have anunsigned long long64-bit integerI want to set some "Variable"-bit positions and get all possible derived numbers E.g. ``` Pattern = 00000000XXXXX000XX000X Positions = 0,4,5,9,10,11,12,13 Result (Pattern, ...
They're too easy. Make a mask of the bit positions you want to stay constant. On each iteration: ``` x |= mask; ++x; x &= ~mask; ```
``` #include <stdio.h> int main(){ char array[2]; array[0] = 'q'; array[1] = 'a'; printf("%s",array); return 0; } ``` if you ask me this code should not work. printf prints array[2] like string but it's not a string. When i execute it, it works perfectly. Can you explain why?
When i execute it, it works perfectly. You just got (un)lucky: your code exhibitsundefined behavior, because it lets theprintf's%sparameter run off the end of the sequence of characters that is not null-terminated. A string in C is a sequence ofchar, which must have an extra character with the value0, called the nul...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. I have simple question.. when I use...
The number of bytes read from the pipe
I know that: ``` char * pword; ``` declares a table which first element is used as a pointer.And ``` *pword <=> * (&pword[0]) <=> pword[0] ``` (Tell me if I'm wrong.) But what I want to know is ifchar*is a type (asintis for integers) and if yes does it represents an address?
Yes,char*is a type, and a variable of that type represents a memory address for achar-type variable (formally a "pointer to char"). TheC data typesarticle on Wikipedia is a good introduction of the various types.
This question already has answers here:Closed10 years ago. Possible Duplicate:How can I allocate a 2D array using double pointers? I used VB 2012 Express to make a maze program. It works really well even when I setROW*COLUMNto499*499, (the maze is an array:unsigned char maze[ROW][COLUMN]). But one time I tried to ...
You are allocatingmazeon the stack, and stack size is typically limited to between 1 and 8 megabytes. To overcome this limitation, allocatemazeon the heap. For suggestions on how to do this, seeHow can I allocate a 2D array using double pointers?andHeap allocate a 2D array (not array of pointers)
Today I came across POSIX thread attributes, they are a little weird work with, when you are using them for the first time. I am a little confused aboutpthread_attr_setdetachstate, which states that: POSIX threads are in Join state (with the thread which created it) by default but in order to join them, we have to ex...
No, you even shouldn't do that: Attempting to detach an already detached thread results in unspecified behavior. So really do either one of them but not both. If you know from the start that you wouldn't joint the thread, use the variant with the attribute. Depending on your system this might save up some time and...
OK, what I'm trying to do may sound a bit complicated, but I still cannot figure it out : Let's say we have anunsigned long long64-bit integerI want to set some "Variable"-bit positions and get all possible derived numbers E.g. ``` Pattern = 00000000XXXXX000XX000X Positions = 0,4,5,9,10,11,12,13 Result (Pattern, ...
They're too easy. Make a mask of the bit positions you want to stay constant. On each iteration: ``` x |= mask; ++x; x &= ~mask; ```
``` #include <stdio.h> int main(){ char array[2]; array[0] = 'q'; array[1] = 'a'; printf("%s",array); return 0; } ``` if you ask me this code should not work. printf prints array[2] like string but it's not a string. When i execute it, it works perfectly. Can you explain why?
When i execute it, it works perfectly. You just got (un)lucky: your code exhibitsundefined behavior, because it lets theprintf's%sparameter run off the end of the sequence of characters that is not null-terminated. A string in C is a sequence ofchar, which must have an extra character with the value0, called the nul...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. I have simple question.. when I use...
The number of bytes read from the pipe
If I run Valgrind cachegrind, will the results with one or more threads be different? Or Valgrind just sequentializes the program and only reports the work of one thread?
Valgrind serializesallthreads in an indeterminate fashion and analyses the sequential code flow. You will receive results about all your code, but the results may not be representative of an actual production run of the same code. (For example, many concurrency-related bugs will not manifest in a program that's run un...
This question already has answers here:Closed10 years ago. Possible Duplicate:Correct way of declaring pointer variables in C/C++ For some time the following has been annoying me, where should I put the star in my pointer notation. ``` int *var; // 1 ``` and ``` int* var; // 2 ``` obviously do the same thing, an...
No. Never.<g> But consider: ``` int* var1, var2; ``` Here, the placement of the*is misleading, because it doesnotapply tovar2, which is anintand not anint*.
Given tmp.c: ``` #include <sys/stat.h> #include <errno.h> #include <stdio.h> int main(int argc, const char *argv[]) { struct stat st; if (stat(argv[1], &st) != 0) { perror("Error calling stat"); } return 0; } ``` I getError calling stat: Value too large for defined data type, when I run...
One needs to#define _FILE_OFFSET_BITS 64: either add it before you#include <sys/stat.h>or define it in your platform-specific way e.g., for gcc see -D option; for Visual Studio go to project properties -> Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions
From C11 draft: C11 (n1570), § K.3.5.1.1 Thetmpfile_sfunctionerrno_t tmpfile_s(FILE * restrict * restrict streamptr); What is the purpose of therestrictqualifier here? Because there is no other parameters, the compiler is able to know thatstreamptris not aliased withoutrestrict, isn't it?
There are several global variables around that have typeFILE*such asstdoutandstderrfor example. So the leftmostrestrictclearly indicates that none of these can be returned, the returnedFILE*doesn't alias with any other. The secondrestrictmakes the same guarantee but one level higher, you are not allowed to pass someth...