question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer... |
ALinux cross reference sitewill help you.
For instance, look atinclude/linux/netlink.h.It has links on each function which will bring up a search window for that function and help you find the definition.
|
I am using "UNIX" (on my virtual machine) and generating ".docx" file there using "C", after getting the file into Windows, when I am opening the file it's saying "the file is corrupted, can't be opened" and then its not opening.
I am using MS-Word 2010.
Here is the piece of code I am using:-
```
Write_to_file(){
... |
Just with an extension name (doc docx) does not make the file a MS word file. Your code is only writing a text file. You can dectect this by file command under Linux.
Please reference thishttp://msdn.microsoft.com/en-us/library/cc313105(v=office.12).aspx, and write theREALMS document file.
|
C has a predefined macro__DATE__, that shows the date of the compiled source file .The date is displayed in the format"Mmm dd yyyy".
Is there any way to be formatted this date, using macros ?In this format"yyyy Mmm dd".
Instead of being :
Jul 19 2013
Should be :
2013 Jul 19
|
In C you could have a macro that generates a compound literal on the fly that has the order that you like, something like
```
#define FDATE (char const[]){ __DATE__[7], __DATE__[8], ..., ' ', ... , '\0' }
```
in all places where it matters your optimizer should be able to handle this efficiently.
|
Is it possible to run a written code or written library that only uses initial c libraries, on every platform?
For example:
Windows,
ARM Microprocessors,
PIC microprocessors,
They have their compilers seperately and this difference is not important for me, I can compile in different compilers for need. B... |
It depends. If your library use only standard C and the multiplatform you are about to port has a compiler compatiable to standard C, you can always write the library code. But if your library have to call native API of each platform, you have to encapsulate these code seperately.
|
If we want to use gets in c we will do something like:
```
int main(void) {
char str[100];
while (gets(str)) {
printf("%s\n",str);
}
}
```
We have to know the length of str first(which is 100) and then use gets. Is it possible using gets without knowing the length of the array in c?
|
If you mean usinggetssafely, no, it's not possible.
Advice: don't usegets, because without knowing the length first, it may cause buffer overflow. Usefgetsinstead, or usegets_sin C11.
In fact,getshas been removed fromstdio.hsince C11. (In C99, it's deprecated)
|
I had a sample code for CUDA VIDEO ENCODING which originally written for windows, after preparing Make file and trying to compile it, it come to error because of HRESULT , LARGE_INTEGER and DWORD data type that they are specific to windows. how can I overcome this problem ?
```
LARGE_INTEGER m_liUserTime0, m_liKerne... |
You could define these types yourself:
```
typedef unsigned long long LARGE_INTEGER;
typedef unsigned long DWORD;
typedef long HRESULT;
```
|
I just started coding in C, and ran someone else's Makefile with the default C compiler set to gcc. I am on Mac OSX 10.8 Mountain Lion and I believe I installed the compiler with "XCode Command Line Tools." After running "make" on command line, I get these annoying .dSYM files for each program. I read that these are d... |
The-gflag to GCC will generate debug symbols. You may simply remove that flag fromCFLAGS.
|
This question already has answers here:What happens here? sizeof(short_int_variable + char_variable)(5 answers)Closed10 years ago.
Given this code snippet:
```
#include <stdio.h>
int main() {
short i = 20;
char c = 97;
printf("%d, %d, %d\n", sizeof(i), sizeof(c), sizeof(c + i));
... |
c + iis an integer expression (integer promotion!), sosizeof()returnssizeof(int)
|
The below program is printing 123828749, 0.000000 but I expected 123828749, 123828749.0. From where it is getting 0.000000 ?
```
#include <stdio.h>
void main()
{
double x = 123828749.66;
int y = x;
printf("%d\n", y);
printf("%lf\n", y);
}
```
Thanks
|
In the second call toprintfyou are passing anint, but the format string is%lfwhich expects a floating point value to be passed. This invokes undefined behaviour.
If you want to treatyas a floating point value when you pass it toprintf, you'll need an explicit conversion:
```
printf("%lf\n", (double)y);
```
|
Which Data Structure should be used for a Library Management Project?
There are 5 operations:
Buy a bookBuy a new copy of a bookRent a bookReturn back a bookdelete a copy of a book
I know Hash Tables and AVL-Trees at the moment.
I started my project with AVL, but I am not sure if it's the right choice.
|
It depends on what you want to achieve(performance, extensibility, simplicity), the above operations can be implemented with simple data structure like array or linked list.
I recommand using simple data structure to implement your application first. When performance become a problem, consider other data structures l... |
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer... |
ALinux cross reference sitewill help you.
For instance, look atinclude/linux/netlink.h.It has links on each function which will bring up a search window for that function and help you find the definition.
|
I am using "UNIX" (on my virtual machine) and generating ".docx" file there using "C", after getting the file into Windows, when I am opening the file it's saying "the file is corrupted, can't be opened" and then its not opening.
I am using MS-Word 2010.
Here is the piece of code I am using:-
```
Write_to_file(){
... |
Just with an extension name (doc docx) does not make the file a MS word file. Your code is only writing a text file. You can dectect this by file command under Linux.
Please reference thishttp://msdn.microsoft.com/en-us/library/cc313105(v=office.12).aspx, and write theREALMS document file.
|
C has a predefined macro__DATE__, that shows the date of the compiled source file .The date is displayed in the format"Mmm dd yyyy".
Is there any way to be formatted this date, using macros ?In this format"yyyy Mmm dd".
Instead of being :
Jul 19 2013
Should be :
2013 Jul 19
|
In C you could have a macro that generates a compound literal on the fly that has the order that you like, something like
```
#define FDATE (char const[]){ __DATE__[7], __DATE__[8], ..., ' ', ... , '\0' }
```
in all places where it matters your optimizer should be able to handle this efficiently.
|
Is it possible to run a written code or written library that only uses initial c libraries, on every platform?
For example:
Windows,
ARM Microprocessors,
PIC microprocessors,
They have their compilers seperately and this difference is not important for me, I can compile in different compilers for need. B... |
It depends. If your library use only standard C and the multiplatform you are about to port has a compiler compatiable to standard C, you can always write the library code. But if your library have to call native API of each platform, you have to encapsulate these code seperately.
|
If we want to use gets in c we will do something like:
```
int main(void) {
char str[100];
while (gets(str)) {
printf("%s\n",str);
}
}
```
We have to know the length of str first(which is 100) and then use gets. Is it possible using gets without knowing the length of the array in c?
|
If you mean usinggetssafely, no, it's not possible.
Advice: don't usegets, because without knowing the length first, it may cause buffer overflow. Usefgetsinstead, or usegets_sin C11.
In fact,getshas been removed fromstdio.hsince C11. (In C99, it's deprecated)
|
I had a sample code for CUDA VIDEO ENCODING which originally written for windows, after preparing Make file and trying to compile it, it come to error because of HRESULT , LARGE_INTEGER and DWORD data type that they are specific to windows. how can I overcome this problem ?
```
LARGE_INTEGER m_liUserTime0, m_liKerne... |
You could define these types yourself:
```
typedef unsigned long long LARGE_INTEGER;
typedef unsigned long DWORD;
typedef long HRESULT;
```
|
In a given code I found following sequence,
```
data = POC_P_Status, TE_OK;
```
I don't understand what that does mean.
Does the data element receive the first or the second element or something else?
Update:
I read somewhere that this behavior is like this,
if i would write that:
if(data = POC_P_Status, TE_OK)... |
It storesPOC_P_Statusintodata.
```
i = a, b; // stores a into i.
```
This is equivalent to
```
(i = a), b;
```
because the comma operator has lower precedence than assignment.
|
Is it right to say that thenullterminating C string is automatically added by the compiler in general?
So in the following example:
```
char * str = "0124";
printf("%x", str[str[3] - str[2] + str[4]]);
```
the output is always 32?
Thanks.
|
First question: yes
Second question: yes on a ASCII system: you calculate'4' - '2' + '\0'which is in integers:0x34 - 0x32 + 0= 2 so you getstr[2]which is'2'which is 0x32.'4' - '2'to be 2 is defined in C, but if you ran your code on an EBCDIC system,'2'was 0xf2
|
I am running Windows 7, and I know the DLL was built using Visual Studio C++ 2010. Since I don't have the source code I can't build it on-the-fly in R when creating a package (NAMESPACE).At this stage, I don't need to create a package, I just want to load the library in R usingdyn.load(). Since it is a dll I suppose i... |
Yes, R can load it usingdyn.load. You may or may not be able to actually call the functions it exports, though. Unless the functions' arguments correspond to what R can handle, they won't be usable. If this is the case, you can write a wrapper dll that acts as a translation layer between it and R.
|
I'm trying to generate every possible 3-digit combination like:012, 013 ,014...
BUT:I want to ignore repeated characters(like 999 or 022)and I also don't want to re-use numbers(if 123 already there, don't display 321)so, the last value should be789.
Here My code :
```
int main()
{
int i;
int j;
for(i=1... |
I think the easiest way to solve this would be something like
```
for (i = 0; i <= 7; i++)
{
for (j = i+1; j <= 8; j++)
{
for (k = j+1; k <= 9; k++)
{
printf("%d%d%d\n", i, j, k);
}
}
}
```
|
I`ve a small app that returns is week even or not.
```
time_t now = time(0);
tm *ltm = localtime(&now);
int twin=(ltm->tm_yday/7)%2
```
But independently from the 1st day of the year so it returns
mon, thu, we, etc0,1,1,1,1,1,1in the next week1,0,0,0,0,0,0In the next yearmon, thu, we, etc0,0,1,1,1,1,1in the next w... |
You are assuming that first week has exactly 7 days which is incorrect.
For example Jan 1st 2013 was Tuesday, so the first week is only 5 days long.
How about using strftime? Something like:
```
time_t now = time(0);
tm *ltm = localtime(&now);
char weekNr[3];
strftime(weekNr, sizeof(weekNr), "%W", ltm);
int isOdd ... |
Is this program legal C? If so, please support your claim (either way) with references to one of the language standards.
```
void f(char *p) {
char *q = p - 1;
(void)( q < p );
};
int main(void) {
char arr[] = "Hello";
f( arr );
}
```
In particular, I'm interested in whether theq < pcomparison is le... |
No, it isn't. Using a pointer which doesn't point to an element of the array or one past its end (i. e. which isn't in the range[&arr[0], &arr[size]]) invokes undefined behavior.
C11 Standard, 6.5.6.8 ("Additive Operators"):
If both the pointer operand and the result [of P + N] point to elements of the same array ob... |
In the following function:
```
double dict(const char *str1, const char *str2) {
```
There is the following:
```
if (strlen(str1) != 0 && strlen(str2) != 0)
while (prefix_length < 3 && equal(*str1++, *str2++)) prefix_length++;
```
What does the operator++do in*str1++and*str2++?
|
The++operator in*str++increments the pointer (not the thing pointed at).
```
(*str)++; /* Increment the character pointed at by str */
*str++; /* Increment the pointer in str */
*(str++); /* Increment the pointer in str - the same, but verbose */
```
There are two very different operations shown (one of them... |
I've been developing a C application that expects wide range of UTF-8 characters, so I started usingICUlibrary to support Unicode characters, but it seems things aren't working nicely with other libraries(mainly, jansson, a JSON library).
Even thoughjanssonclaims it fully supports UTF-8, it only expects chars as para... |
Get ICU to produce output in UTF-8 usingtoUTF8/toUTF8String. (toUTF8String gives you astd::stringso.c_str()to get thechar*that Jansson wants.
|
This question already has answers here:atoi() — string to int(5 answers)Closed10 years ago.
Someone told me that I shouldn't useatoi(), and that I should always usestrtol()instead. What's wrong withatoi()that I shouldn't use it? Isstrtol()really the right thing to use instead? (And what about the fact thatstrtol()ret... |
from your ownlink:
The atoi() function is subsumed by strtol() but is retained because it is used extensively in existing code.If the number is not known to be in range, strtol() should be used because atoi() is not required to perform any error checking.
Or
atoiis obsolete
|
My "mothertongue" is Java, and I need to write a project in C in educational purposes. I try to understand thequeue.hlibrary. In Java by default youadd()an item to the end of theList, however inqueue.hthere is onlyLIST_INSERT_HEADmacro that doesn't accept other members. In fact, a small test shows that it inserts to t... |
List in Java corresponds to theList ADT: "an ordered sequence of values, where the same value may occur more than once".
LIST in queue.h is also a List ADT, in which you can see the implementation details (it is implemented as a doubly linked list). It is LIFO, as the very queue.h file states (though quite murkily). ... |
I use atmega168a and configure fuse on Tools > device programming > AVR dragon > fuses > (click on) CKDIV8 to set it to 8 MHz internal clock.
what piece of code do I need to add to my C code to be able to set that fuse?
|
If you set the fuse externally, as a separate step, you don't need any further code in C.If you set the fuse programmatically, you don't need to set the fuse externally. Now (each) program decides, at run-time. This code is for atmega32u2:
CLKPR = 1 << CLKPCE;// Set prescaler to 1CLKPR = 0;
In both cases, you shou... |
I have seen in several pieces of code a string declared as char*. How does this work, surely it is a pointer to a single char, not an array of chars which makes up a string. If I wished to take string input to a method that would be called like this:
```
theMethod("This is a string literal");
```
What datatype shoul... |
surely it is a pointer to a single char, not an array of chars
It's a pointer to the first character of an array ofchar. One can access each element of the array using a pointer to its first element by performing pointer arithmetic and "array" indexing.
What datatype should the parameter be?
const char *, if you do... |
how i print the value of the address returned by the function ioremap_nocache with printk?
```
void * ioremap_nocache (unsigned long phys_addr, unsigned long size);
```
http://mirror.linux.org.au/linux-mandocs/2.6.4-cset-20040312_2111/ioremap_nocache.html
I need to know the value of the virtual address stored to de... |
You can use both%luor%pto print a pointer. They have different representation
```
void *pointer = ioremap_nocache(phys_addr, size);
unsigned long cast = pointer;
printk("%lu - %p", cast, pointer); // '15294563 - 0x499602d2'
```
This work also withprintf()
|
is there an elegant way of parsing .conf file in a c program? say, if i have normal text file -
```
param1 = 22
param2 = 99
param34 = 11
param11 = 15
...
```
it'd be nice to get access in one function call, smth like:
```
int c = xfunction(my.conf, param34);
```
and now c = 11. Many thanks in advance.
|
```
#include <stdio.h>
#include <stdlib.h>
#define xfunction(file, param) \
system("awk '/^" #param " = [0-9]+$/{ num = $3 };END { exit num }' " #file)
int main(void){
int c = xfunction(my.conf, param34);
printf("%d\n", c);
return 0;
}
```
|
I compiled a C program (which has some assembly language instructions) like this.
```
TCC -Emasm.exe protect.c
```
It gives an errorUnable to execute masm.exe.
What should I do or where can I findmasm.exe?
|
You need to get microsoft assembly compiler, which is called masm.
|
I need to unpack information in python from a C Structure,
doing it by the following code:
```
struct.unpack_from('>I', file.read(4))[0]
```
and afterwards, writing changed values back:
```
new_value = struct.pack('>I', 008200)
file.write(new_value)
```
a few examples:
008200 returns an syntaxerror: invalid token.... |
This is invalid python code and is not related to the struct module. In python, numbers starting with a zero are octal (base 8). So, python tries to decode 008200 in octal but '8' isn't valid. Assuming you wanted decimal, use 8200. If you wanted hex, use 0x8200.
|
I am trying to write to student.dat file.My problem is when i am writing second time my first data is clearing out.please help me
```
student st;
FILE* fp = fopen("d:\\student.dat", "w");
//fseek(fp,0,SEEK_SET);
st.getdata();
fwrite((char *) &st,sizeof(student),1,fp);
fclose(fp);
printf("\n\nStudent record ... |
Try append mode:
```
FILE* fp = fopen("d:\\student.dat", "a");
```
wmode overwrites file: "Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file."
|
This question already has answers here:Length of array in function argument(9 answers)Closed10 years ago.
I'm a beginner of c and I'm not sure if I do it correctly.
```
char new_str[2000];
void ini(char a[]){
for (int i=0;i<2000;i++) {
a[i] = new_str[i];
}
}
int main(void)
{
char buf[2000];
ini(b... |
if you want to find the size of the character array, you can use
sizeof(buf)/sizeof(buf[0])
Pass this value as the second argument to the ini() function.
So the code should be:
```
void ini(char a[], size_t size)
{
for (int i=0; i<size; i++)
{
a[i] = 0;
}
}
int main(void)
{
char buf[2000];
... |
I saw some C code like this:
```
int check = 10:
switch(check) {
case 1...9: printf("It is 2 to 9");break;
case 10: printf("It is 10");break;
}
```
What does thiscase 1...9:mean? Is it standard?
|
It's a GNU C extension calledcase range.
http://gcc.gnu.org/onlinedocs/gcc/Case-Ranges.html
As noted in the document, you have to put spaces between the low and high value of the range.
```
case 1 ... 9:
statement;
```
is equivalent to:
```
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case ... |
I have variable that must be 16 bit long. How should I define it to be exactly 16 bit independently on the platform?
I can define it asshort, but depending on the platform it can be 16 bits or more.
|
Assuming you're using C99, then useuint16_t(orint16_t) from<stdint.h>. These are guaranteed to exist so long as the compiler has an underlying 16-bit type available.
|
I've two functions:
```
void foo0(int bar);
void foo1(int bar);
```
I wan't to be able create a macroQUXthat will expand to these function names based on another macroBAZ. I tried the following:
```
#define BAZ 0
#define QUX(x) foo##BAZ(x)
```
But it did not work since the generated function wasfooBAZ(). How can I... |
```
#define CAT_I(a,b) a##b
#define CAT(a,b) CAT_I(a, b)
#define QUX(x) CAT(foo, BAZ) ## (x)
```
|
I have a program that renders a 3D wire mesh model using this code fragment in a loop.
```
glBegin(GL_LINES);
glColor3f(.0f, 0.0f, 0.0f);
glVertex3d(xs,ys,zs);
glVertex3d(xe,ye,ze);
glEnd();
```
I need to add functionality so that the vertices where the line starts and ends can be rendered if the user desires, proba... |
You can useGL_POINTSin yourglBegintogether withglPointSizefunction.
|
While I examine the source code of ffmpeg, I see this line:
```
enum AVDurationEstimationMethod av_fmt_ctx_get_duration_estimation_method
(const AVFormatContext* ctx);
```
What is the functionality ofenumhere?
|
av_fmt_ctx_get_duration_estimation_methodis a function which returns an object of enum typeAVDurationEstimationMethod.
|
We are writing a Webkit-based software framework which has a C-backend. We want to pass references from the C layer to the javascript layer at the top. Unfortunately C pointers may be up to 64-bit while javascript only supports up to 56-bit.
How can we overcome this javascript-limitation ?
Our current approach is cr... |
You might simply convert the pointers to doubles in the C side (seethis related question) , and communicate with JavaScript only doubles. There won't be any loss this way as you'll only deal with IEEE754 double precision numbers whose possible values are the same both side.
But experience shows that exchanging pointe... |
What isffreestandingin gcc ? What is it used for ? I came across the following :
```
gcc -ffreestanding -m32 -c kernel.c -o kernel.o
```
and do not understand, what does it mean exactly.
|
Afreestandingenvironment is one in which the standard library may not exist, and program startup may not necessarily be at "main". The option-ffreestandingdirects the compiler tonotassume that standard functions have their usual definition.
By default, GCC will act as the compiler for a hosted implementation, definin... |
I wrote a C program to evaluate reverse polish notation by passing the expression as a command line argument, but when I pass * (for multiplication) then it is passing all the file names in that folder.
For example I passed this :
./rpn 10 20 30 + *
and when I print all the arguments result is,
```
10
20
30
+
... |
This is not a C problem. You're using Bash (or some equivalent shell), where*is automatically expanded (before it gets anywhere near your program). You'll need to do something like this:
```
./rpn 10 20 30 + "*"
```
|
I am trying to add an item to the end of a linked list, or simply add an item if the linked list is empty.
So far I have
```
struct node* curr=head;
struct node* newnode=malloc(sizeof(struct node));
newnode->data=item;
newnode->next=NULL;
if (curr == NULL){
curr=newnode;
}
else {
while(curr->next == NULL){
... |
This won't work
```
if (curr == NULL){
curr=newnode;}
```
You need this:
```
if (curr == NULL){
head=newnode;}
```
The way you had it curr is a local variable pointing to the new element and goes away with the function return. You never keep track of a new one.
And as others have said you need!=in the loop... |
I have read about usingsampler2DRectandtexture2DRectto use rectangular textures. My question is whether its use is recommended for creating sprites 2D using GLSL, or if there is another alternative to using images that are not necessarily a power of two.
|
If all you need arenon-power-of-two textures, that's something OpenGL has supported foralltexture types since GL 2.0. So you don't need rectangle textures if NPOTs are all you want.
|
I'm working with a code base that has a lot of macro that got defined and undefined and redefined all over the place. The compiler surprisingly is still able to chew through them, so is there anyway to extract this kind of macro expansion result , i.e.
```
MY_MACRO -> myFolder/myFile.cpp #266 float myFunc()
```
Is t... |
You can usegcc -Efor GNU C/C++
For Visual Studio, you can useCL /EP /C myfile.cppfrom a command prompt.
|
I was trying to write a simple code which acts as sizeof (specifically for int in this code). But why is it showing 1 as output? It should be 4.
```
#include<stdio.h>
int SIZEOF(int *);
int main(void)
{
int a;
printf("Size is:%d bytes\n",SIZEOF(&a));
return 0;
}
int SIZEOF(int *p1)
{
int *p2;
p... |
Pointer arithmetic works in units of the size of the pointed-to type. When you dop1 - p2, you get the number ofintunits, not the number ofcharunits. Add some casts:
```
return (char *)p1 - (char *)p2;
```
Editorial note:SIZEOFshould probably returnptrdiff_torsize_t.
|
This question already has answers here:Is a += b more efficient than a = a + b in C?(7 answers)Closed10 years ago.
what is the difference betweeni = i + j; andi += j; in C?
Are they equivalent? Is there any side effect ofi?
I was trying to check the assignment mechanism in C using the GCC compiler.
|
They're almost the same. The only difference is thatiis only evaluated once in the+=case versus twice in the other case.
|
First, my code:
```
#include <stdio.h>
int main(){
int a;
char b;
printf("Insert number: ");
scanf_s("%i",&a);
getchar();
printf("Insert character: ");
scanf_s("%c",&b);
printf("Number: %i\n",a);
printf("Character: %c\n",b);
getchar();
getchar();
return 0;
}
```
I use scanf_s... |
You must specify the size of the input string or character inscanf_s.
change
```
scanf_s("%c",&b);
```
to
```
scanf_s("%c", &b, 1);
```
|
Sorry if this is a duplicate, I couldn't find exactly what I want.
I have the current value of a byte:
00110001 A
And I have to write another value:
10001001 B
but in the 2nd byte only some bits
are relevant. The relevant bits
are the ones with a one in this bit
11000000 C
The final byte will be B on the bit... |
Mask and combine:
```
finalByte = (B & C) | (A & ~C);
```
To break down how it works - the result ofB & Cis a byte containing all of the bits ofBwhere bits ofCare set (a normal masking operation).A & ~Cyields a byte with all of the bits ofAwhere bits ofCare cleared - hence the~complement operation. The|combines the... |
My Android App using native functions to communicate with an usb-device. These native functions initiate the connection by using a Handle, i have to use chmod 777 the usb-device to be able to access it. The connection seems to initiate well with my tool.
Without chmod all callbacks work fine, but the connection can't ... |
Solved. I've threaded the initiating in one thread and the callback in a different thread.
|
Say I have a buffer which stores 2 bytes:
```
char *buf=new char[4];
// 00000010 00000000 (.. other stuff ..)
```
What I want to do is switching the least with the most significant byte, and store that value in a variable. Trying to do so as follows:
```
short len=buf[1];
len <<= 8;
len |= buf[0];
// Result, as... |
Your implementation obviously usestwo's complementrepresentation of signed numbers. Use unsigned values instead
```
unsigned char * buf = new unsigned char[2];
...
unsigned short len=buf[1];
len <<= 8;
len |= buf[0];
```
|
What isffreestandingin gcc ? What is it used for ? I came across the following :
```
gcc -ffreestanding -m32 -c kernel.c -o kernel.o
```
and do not understand, what does it mean exactly.
|
Afreestandingenvironment is one in which the standard library may not exist, and program startup may not necessarily be at "main". The option-ffreestandingdirects the compiler tonotassume that standard functions have their usual definition.
By default, GCC will act as the compiler for a hosted implementation, definin... |
I wrote a C program to evaluate reverse polish notation by passing the expression as a command line argument, but when I pass * (for multiplication) then it is passing all the file names in that folder.
For example I passed this :
./rpn 10 20 30 + *
and when I print all the arguments result is,
```
10
20
30
+
... |
This is not a C problem. You're using Bash (or some equivalent shell), where*is automatically expanded (before it gets anywhere near your program). You'll need to do something like this:
```
./rpn 10 20 30 + "*"
```
|
I am trying to add an item to the end of a linked list, or simply add an item if the linked list is empty.
So far I have
```
struct node* curr=head;
struct node* newnode=malloc(sizeof(struct node));
newnode->data=item;
newnode->next=NULL;
if (curr == NULL){
curr=newnode;
}
else {
while(curr->next == NULL){
... |
This won't work
```
if (curr == NULL){
curr=newnode;}
```
You need this:
```
if (curr == NULL){
head=newnode;}
```
The way you had it curr is a local variable pointing to the new element and goes away with the function return. You never keep track of a new one.
And as others have said you need!=in the loop... |
I have read about usingsampler2DRectandtexture2DRectto use rectangular textures. My question is whether its use is recommended for creating sprites 2D using GLSL, or if there is another alternative to using images that are not necessarily a power of two.
|
If all you need arenon-power-of-two textures, that's something OpenGL has supported foralltexture types since GL 2.0. So you don't need rectangle textures if NPOTs are all you want.
|
I'm working with a code base that has a lot of macro that got defined and undefined and redefined all over the place. The compiler surprisingly is still able to chew through them, so is there anyway to extract this kind of macro expansion result , i.e.
```
MY_MACRO -> myFolder/myFile.cpp #266 float myFunc()
```
Is t... |
You can usegcc -Efor GNU C/C++
For Visual Studio, you can useCL /EP /C myfile.cppfrom a command prompt.
|
I was trying to write a simple code which acts as sizeof (specifically for int in this code). But why is it showing 1 as output? It should be 4.
```
#include<stdio.h>
int SIZEOF(int *);
int main(void)
{
int a;
printf("Size is:%d bytes\n",SIZEOF(&a));
return 0;
}
int SIZEOF(int *p1)
{
int *p2;
p... |
Pointer arithmetic works in units of the size of the pointed-to type. When you dop1 - p2, you get the number ofintunits, not the number ofcharunits. Add some casts:
```
return (char *)p1 - (char *)p2;
```
Editorial note:SIZEOFshould probably returnptrdiff_torsize_t.
|
This question already has answers here:Is a += b more efficient than a = a + b in C?(7 answers)Closed10 years ago.
what is the difference betweeni = i + j; andi += j; in C?
Are they equivalent? Is there any side effect ofi?
I was trying to check the assignment mechanism in C using the GCC compiler.
|
They're almost the same. The only difference is thatiis only evaluated once in the+=case versus twice in the other case.
|
First, my code:
```
#include <stdio.h>
int main(){
int a;
char b;
printf("Insert number: ");
scanf_s("%i",&a);
getchar();
printf("Insert character: ");
scanf_s("%c",&b);
printf("Number: %i\n",a);
printf("Character: %c\n",b);
getchar();
getchar();
return 0;
}
```
I use scanf_s... |
You must specify the size of the input string or character inscanf_s.
change
```
scanf_s("%c",&b);
```
to
```
scanf_s("%c", &b, 1);
```
|
Sorry if this is a duplicate, I couldn't find exactly what I want.
I have the current value of a byte:
00110001 A
And I have to write another value:
10001001 B
but in the 2nd byte only some bits
are relevant. The relevant bits
are the ones with a one in this bit
11000000 C
The final byte will be B on the bit... |
Mask and combine:
```
finalByte = (B & C) | (A & ~C);
```
To break down how it works - the result ofB & Cis a byte containing all of the bits ofBwhere bits ofCare set (a normal masking operation).A & ~Cyields a byte with all of the bits ofAwhere bits ofCare cleared - hence the~complement operation. The|combines the... |
My Android App using native functions to communicate with an usb-device. These native functions initiate the connection by using a Handle, i have to use chmod 777 the usb-device to be able to access it. The connection seems to initiate well with my tool.
Without chmod all callbacks work fine, but the connection can't ... |
Solved. I've threaded the initiating in one thread and the callback in a different thread.
|
Say I have a buffer which stores 2 bytes:
```
char *buf=new char[4];
// 00000010 00000000 (.. other stuff ..)
```
What I want to do is switching the least with the most significant byte, and store that value in a variable. Trying to do so as follows:
```
short len=buf[1];
len <<= 8;
len |= buf[0];
// Result, as... |
Your implementation obviously usestwo's complementrepresentation of signed numbers. Use unsigned values instead
```
unsigned char * buf = new unsigned char[2];
...
unsigned short len=buf[1];
len <<= 8;
len |= buf[0];
```
|
This question already has answers here:how to use #ifdef with an OR condition?(2 answers)How do I check if one of multiple macros is defined in a single #ifdef?(2 answers)Closed10 years ago.
I suppose you can add code which will get executed only if 2 terms are simultaneously declared this way:
```
#ifdef X
#ifdef Y... |
Usingdefined:
```
#if defined(X) || defined(Y)
```
|
I couldn't find exact answer to this question so I am posting it here:
If I have an integer range, I want to calculate "N" numbers in this range at equal logarithmic distance.
Here is a sample code to find numbers at equal "non-logarithmic" distance (more or less):
```
const int N = 100; // total no of sizes to gene... |
I can only guess what you really want is a logarithmic scale.
In that case, instead of adding a constantGAP, you multiply by a constantFACTOR.
The FACTOR can be found by solving the equationLOW*FACTOR^N=HIGHforFACTOR.
It turns out the solution is the N'th root of HIGH/LOW.
|
I am getting following warning even after including<stdlib.h>
warning: incompatible implicit declaration of built-in function ‘exit’
Is anybody know why it is giving?
```
void Check_file(char *filepath)
{
if(access( filepath, F_OK ) == -1 ) {
printf("\nUnable to access : %s\n",filepath);
... |
Your programcompiles without complaintwhen the proper include files are provided.
```
#include <stdio.h> /* needed for printf */
#include <stdlib.h> /* needed for exit */
#include <unistd.h> /* needed for access and F_OK */
void Check_file(char *filepath)
{
if(access( file... |
Can someone explain how we calculate the value of Hexadecimal Floating point constant.
I was reading a book and found 0x0.3p10 represents the value 192.
|
The exponent is still expressed in decimal, but the base is two, and the mantissa is in hex.
So 0.3P10 is (3 × 16−1) × 210, which is 3/16 × 210, which is 3 × 26= 192.
Each hex digit of the mantissa gobbles up four units of exponent, since 16 = 24.
|
I have declared a matrix and then calculated the average of all the elements like this
```
CvMat* rgb1 = cvCreateMat(5, 5, CV_32FC1);
// declared the elements of rgb1//
CvScalar avg = cvAvg(rgb1); //calculated the average of all elements of rgb1 matrix
```
How can I subtract the average value (avg) ... |
You can usecvSubS()to subtract a scalar value from each element of an image:
```
cvSubS(rgb1, avg, rgb1);
```
|
I'm trying to compilelibpng, which requires thelibz. I have installed my ownerlibz.so.1at my home and set theLD_LIBRARY_PATH.But it does not get any result because the output oflddshows that it still uses/usr/local/lib/libz.so.1.
And then the output of make shows like "-L/home/zlib -lz". Why?
|
Probably you need a symbolic link from/home/mylibs/libz.soto/home/mylibs/libz.so.1.
Note that-lzwill search forlibz.so, but notlibz.so.1, so the linker will keep on searching and will find such a link in/usr/local/lib.
Other than that, you make want to show the NEEDED entries (which record dynamic dependencies) in t... |
I am new to this forum so please go easy on me :)
I have the following in my code
```
#define SYS_SBS 0x02
```
Whenever I try to use this and try to output,I get 2 as the value, however I want to get SYS_SBS as the output for my program. Is there a way, I can do this.
I have no control over the source code. I ... |
```
#include <stdio.h>
#define SYS_SBS 0x02
#define id(x) #x
int main(){
printf("%s %d\n", id(SYS_SBS), SYS_SBS);
return 0;
}
```
|
Using OpenCV's,Clanguage based API, I need to calculate sum of all elements in an OpenCV array. I use thesum(1) method. Below is what I have tried.
```
/* rgb1 is an OpenCV array */
CvScalar cvSum( const CvArr* rgb1);
printf("%lf", CvScalar.val);
```
But I get compiler error aserror: expected primary-expression befo... |
'val'is an array ofdoubles. You need to access it viaval[0], andprintfit using%f
You also have a bug. What you wrote in not valid C code.It should be this:
```
CvScalar sum = cvSum(rgb1);
printf("%f", sum.val[0]);
```
or if you don't want the variable:
```
printf("%f", cvSum(rgb1).val[0]);
```
|
Given a C function:
```
void f(T x, T y) {
x = y;
}
```
I want to make sure that all instances of T assignments will fail. So far, the best solution I have is something like:
```
#define T const void *
```
is there a better solution? (Ideally I would like T to be defined as some kind of a non-assignable opaque... |
typedefis more suitable here.
For immutable data:typedef const void * T;
For immutable pointer:typedef void * const T;
|
I have 3D OpenGL application written in C for Unix-like systems, it is working fine in Linux, but lacks GUI and is only controllable via keyboard.
As far as I know C# GUI is the simplest and nicest and cutest to create and it's very easy to create nice gui in C# in Microsoft Visual Studio 2010 Ultimate.
SO I decided ... |
You are probably going to need to create a managed code wrapper for your C project so that it can be accessed from C#.
See this previously asked question:Porting (unmanaged) C++ to C# vs. using the C++ as a DLL in a C# application
|
This question already has answers here:What does a comma separated list of values, enclosed in parenthesis mean in C? a = (1, 2, 3); [duplicate](6 answers)How does the Comma Operator work(9 answers)Closed10 years ago.
Please consider following code,
```
int i;
i = 1,2,3,4,5;
printf("First time i = %d\n",i);... |
First one is equivalent to(i = 1),2,3,4,5;which means the commas have no effect. When used with parentheses it returns the last value in the "comma delimited list"
This is all due to operator precedence, which you can view a table abouthere
|
According to my knowledge, local variables are uninitialized i.e, it contains garbage value.
But following program is giving 0 (zero) as output.
```
main()
{
int i;
printf("%d\n",i);
}
```
When i run above program it is giving always 0.
I know that 0 is also can be a garbage value but every time i am getting... |
Garbage value means whatever happened to be in that memory location. In your case, the value happened to be zero. It may not be the case in another machine.
Note that some compiler will fill uninitialized variable with some magic value for the purpose of debugging (like0xA5A5), but it's usually not zero, either.
|
I have a.c b.cpp files.
```
/****** a.c ******/
fun1(...)
{
..........
fun2(...); /* function present in b.cpp */
..........
}
/******* b.cpp *******/
extern "C" int fun2(...);
int fun2(...)
{
..........
}
```
I have compiled the code as follows:
```
a.o:a.c b.o
gcc -c -o a.o a.c b.o
b.o... |
You need to add a prototype of the function in a.c.
|
My C program runs on Solaris and needs to restart itself when some condition occurs, such as receiving a signal. Now I consider to use exec family functions to implement this features, and there are 3 issues:
I know the file descriptors should be closed before execing, but program uses some third-party libraries, and... |
I would have 2 programs ... one is a launcher of the second one. The launcher is waiting for the return value of the second program, and based on this value it decides to relaunch it or not.
|
As recommended by pygtk itself, the way forward is GObjectIntrospection. I would like to port a C API for python which uses pygtk.h and pygobject.h. Can anyone show me the way towards documentation on how to do this ?
|
Actuallypygtk_init()andpygobject_init()are macros found in pygtk headers. We should useinit_pygobject()function which takes 3 arguments major, minor and micro which are version numbers or (-1, -1, -1) which is kinda default should work. Also inorder to smoothly run your ported app you may requirePySys_SetArgv(0, "[]")... |
Running Debian 7.
Is it possible that when a program opens a file we can give it output from a currently running file.
Example:
We have a C/Java program running. This is (attached)? to file /etc/motd as an example.
When ssh or any other program goes to read /etc/motd the C/Java program provides output instead. So ins... |
You would create /etc/motd as a special device file, not as a regular text or binary file. Then, you would attach your program to the device file with a pipe and have it waiting for input. Once input was received the program would then process the data and do the commands required. Items to refer to are: mknod and |... |
By the declaration
```
const int i;
```
it is clear thaticannot be modified.Then why does the declaration
```
void f (const int *p)
```
is modifyingp? ( I tested it, it is modifyingpbut don't know how?).
|
The placement ofconstin a pointer declaration matters. You read it backwards:
const int *pmeans "p is a pointer tointwhich is constant"int * const pmeans "p is a constant pointer toint"const int * const pmeans "p is a constant pointer to a constantint"
|
Why is
```
int i;
int *p = &i;
```
right, while
```
int i, *p;
*p = &i;
```
is wrong?
Is there any difference between*operator used in declaration (int *p = &i) and expression (*p = &i)?
|
In your second code block, this:
```
int i, *p;
*p = &i;
```
can be fixed to:
```
int i, *p;
p = &i;
```
pis still declared as a pointer to anint, but you want to store the address ofitop.
In your code,*p = &istores the address ofito some area in memory thatppoints to (since you didn't initialize it).
|
I have a long list of variable for private and share. How do I write in multiple lines? I am repeating the question here, just because stackoverflow wouldn't let me submit the question otherwise.
|
Pragmas are interpreted by the compiler after preprocessing, so you can just use the normal line-continuation mechanism:
```
#pragma omp parallel
```
can become:
```
#pragma \
omp \
parallel
```
|
I started to read a few articles about pointers in C and I've got one example that I don't understand.
What should be the output of following code..??
```
main()
{
char far *s1 ,*s2;
printf("%d,%d",sizeof(s1),sizeof(s2));
}
```
OUTPUT-4,2
According to me, value returned by both sizeof() functi... |
It's the same as writing
```
char far *s1;
char *s2;
the "far" is not distributed across all variables, e.g.
char far *s1, ch;
```
far makes no sense on a normal character ch.
Hence s2 is not a "far" pointer, and is handled as a "near" pointer, which is 16 bits wide in your target.
|
```
typedef struct_t struct_array[ROWS][COLS];
int main()
{
struct_array structArray1 = {0};
}
```
I got an error saying there is a missing braces around the initializer. I know there is a bug of gcc regarding this warning. Or am I doing something wrong?
|
You need to usestruct_array structArray1 = {{{0}}};, the first one for the 1st dimension of the array, the 2nd one for the 2nd dimension and the third for the struct initialization. The code is right, but your GCC is buggy as stated in other answers.
|
```
#include<stdio.h>
#include<stdlib.h>
void main(){
exit(0);
}
```
This is my code in c how could I make the console exit??I have tried to use the exit function but it seems like it doesn't work
|
exitcausesyour programto exit, not the shell that you ran it from. Your program is equivalent to:
```
int main(void)
{
return 0;
}
```
You might want to look intokill(2).
Editorial note:mainshould returnint, notvoid.
|
is there any function in go that is similar like"_file_"or"_line_"in go, to know who is calling a specific function during run time? In C we have the"_file_"line that can be called as macros. How to do this in go?
|
If you're using thelogpackage, you can instruct the logger toprefix the entries with various information. You'll likely be most interested in theLshortfileconstant, which will result in prefixes along the lines ofd.go:23. Alternatively, there isLlongfilewhich prints the file's full path (such as/a/b/c/d.go:23).
If yo... |
I am following the "Smashing the Stack for fun and profits"http://insecure.org/stf/smashstack.html.
I wonder why my code is working though I wrote it to make a segmentation fault.
```
#include <stdio.h>
#include <string.h>
void function(char *str){
char buffer[16];
strcpy(buffer, str);
}
int main(void)
{
... |
It's just because yourlarge_stringis not initialized properly: it contains garbage, and its length (number of bytes till'\0') is most probably much less than 256 (e.g. on my machine the fourth byte oflarge_stringis zero sostrcpycopies just 4 bytes).
Make it
```
for(i = 0; i < 254; i++)
large_string[i] = 'A';
lar... |
I would like to use strcmp to find a specific character on a char array. For example, I would like to detect the index number where.is on the text.
```
char host[100] = "hello.world";
size_t i=0;
for(i=0;i<strlen(host);i++){
if(strcmp(host[strlen(host)-i], ".")){
printf("%d\n",i);
}
}
```
however, it o... |
Since it appears you want to scan the string backwards, you could do:
```
char host[100] = "hello.world";
size_t ii=0;
for(ii=strlen(host); ii--;){
if(host[ii] == '.') { // compare characters, not strings
printf("%zu\n", ii);
}
}
```
This has the additional advantage of callingstrlen()only once (the ... |
I have a function that returns me a string asconst char *:
```
const char* get_text();
```
I need to call a functionAfxMessageBox(LPCTSTR text).
How can I convert the string that I got byget_text()?
|
As you're using MFC and assuming a UNICODE build (or you wouldn't have this error!), probably the simplest way is to instantiate awchar_tcompatibleCStringdirectly:
```
CStringW szWide(getText());
AfxMessageBox(szWide);
```
|
I am using this compare function to sort an array consisting of long long int nos.
```
int compare(const void * p1,const void * p2)
{
return (* (long long int * )a-*(long long int * )b);
}
qsort(array,no of elements,sizeof(long long int),compare)
```
this works fine for small nos but when the array contains nos ... |
The result ofcomparefunction must beint. The subtraction of twolong longcan easily overflow theinttype (and it does in your case).
Try comparing the two values explicitly and returning -1, 0 or 1.
|
Suppose to have a__m128variable holding 4 SP values, and you want the minimum one, is there any intrinsic function available, or anything other than the naive linear comparison among the values?
Right know my solution is the following (suppose the input__m128variable isx):
```
x = _mm_min_ps(x, (__m128)_mm_srli_si12... |
There is no single instruction/intrinsic but you can do it with two shuffles and two mins:
```
__m128 _mm_hmin_ps(__m128 v)
{
v = _mm_min_ps(v, _mm_shuffle_ps(v, v, _MM_SHUFFLE(2, 1, 0, 3)));
v = _mm_min_ps(v, _mm_shuffle_ps(v, v, _MM_SHUFFLE(1, 0, 3, 2)));
return v;
}
```
The output vector will contain ... |
This question already has answers here:What does a comma separated list of values, enclosed in parenthesis mean in C? a = (1, 2, 3); [duplicate](6 answers)How does the Comma Operator work(9 answers)Closed10 years ago.
Please consider following code,
```
int i;
i = 1,2,3,4,5;
printf("First time i = %d\n",i);... |
First one is equivalent to(i = 1),2,3,4,5;which means the commas have no effect. When used with parentheses it returns the last value in the "comma delimited list"
This is all due to operator precedence, which you can view a table abouthere
|
According to my knowledge, local variables are uninitialized i.e, it contains garbage value.
But following program is giving 0 (zero) as output.
```
main()
{
int i;
printf("%d\n",i);
}
```
When i run above program it is giving always 0.
I know that 0 is also can be a garbage value but every time i am getting... |
Garbage value means whatever happened to be in that memory location. In your case, the value happened to be zero. It may not be the case in another machine.
Note that some compiler will fill uninitialized variable with some magic value for the purpose of debugging (like0xA5A5), but it's usually not zero, either.
|
I have a.c b.cpp files.
```
/****** a.c ******/
fun1(...)
{
..........
fun2(...); /* function present in b.cpp */
..........
}
/******* b.cpp *******/
extern "C" int fun2(...);
int fun2(...)
{
..........
}
```
I have compiled the code as follows:
```
a.o:a.c b.o
gcc -c -o a.o a.c b.o
b.o... |
You need to add a prototype of the function in a.c.
|
My C program runs on Solaris and needs to restart itself when some condition occurs, such as receiving a signal. Now I consider to use exec family functions to implement this features, and there are 3 issues:
I know the file descriptors should be closed before execing, but program uses some third-party libraries, and... |
I would have 2 programs ... one is a launcher of the second one. The launcher is waiting for the return value of the second program, and based on this value it decides to relaunch it or not.
|
As recommended by pygtk itself, the way forward is GObjectIntrospection. I would like to port a C API for python which uses pygtk.h and pygobject.h. Can anyone show me the way towards documentation on how to do this ?
|
Actuallypygtk_init()andpygobject_init()are macros found in pygtk headers. We should useinit_pygobject()function which takes 3 arguments major, minor and micro which are version numbers or (-1, -1, -1) which is kinda default should work. Also inorder to smoothly run your ported app you may requirePySys_SetArgv(0, "[]")... |
Running Debian 7.
Is it possible that when a program opens a file we can give it output from a currently running file.
Example:
We have a C/Java program running. This is (attached)? to file /etc/motd as an example.
When ssh or any other program goes to read /etc/motd the C/Java program provides output instead. So ins... |
You would create /etc/motd as a special device file, not as a regular text or binary file. Then, you would attach your program to the device file with a pipe and have it waiting for input. Once input was received the program would then process the data and do the commands required. Items to refer to are: mknod and |... |
By the declaration
```
const int i;
```
it is clear thaticannot be modified.Then why does the declaration
```
void f (const int *p)
```
is modifyingp? ( I tested it, it is modifyingpbut don't know how?).
|
The placement ofconstin a pointer declaration matters. You read it backwards:
const int *pmeans "p is a pointer tointwhich is constant"int * const pmeans "p is a constant pointer toint"const int * const pmeans "p is a constant pointer to a constantint"
|
Why is
```
int i;
int *p = &i;
```
right, while
```
int i, *p;
*p = &i;
```
is wrong?
Is there any difference between*operator used in declaration (int *p = &i) and expression (*p = &i)?
|
In your second code block, this:
```
int i, *p;
*p = &i;
```
can be fixed to:
```
int i, *p;
p = &i;
```
pis still declared as a pointer to anint, but you want to store the address ofitop.
In your code,*p = &istores the address ofito some area in memory thatppoints to (since you didn't initialize it).
|
I have a long list of variable for private and share. How do I write in multiple lines? I am repeating the question here, just because stackoverflow wouldn't let me submit the question otherwise.
|
Pragmas are interpreted by the compiler after preprocessing, so you can just use the normal line-continuation mechanism:
```
#pragma omp parallel
```
can become:
```
#pragma \
omp \
parallel
```
|
I started to read a few articles about pointers in C and I've got one example that I don't understand.
What should be the output of following code..??
```
main()
{
char far *s1 ,*s2;
printf("%d,%d",sizeof(s1),sizeof(s2));
}
```
OUTPUT-4,2
According to me, value returned by both sizeof() functi... |
It's the same as writing
```
char far *s1;
char *s2;
the "far" is not distributed across all variables, e.g.
char far *s1, ch;
```
far makes no sense on a normal character ch.
Hence s2 is not a "far" pointer, and is handled as a "near" pointer, which is 16 bits wide in your target.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.