question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
In C++, if an object of a class is passed as a parameter into a function, the copy constructor of the class will be called.
I was wondering if the object is of nonclass type, what function will be called?
Similarly in C, what function is called when passing values or address of variables into a function?
Thanks and regards!
|
No function will be called; the bytes composing the object will simply be copied to the correct place for the callee (be that a location in memory or a register).
|
In a C struct I have defined a function pointer as follows:
```
typedef struct _sequence_t
{
const int seq[3];
typedef void (* callbackPtr)();
} sequence_t;
```
I want to initialize a var of that type globally with:
```
sequence_t sequences[] = {
{ { 0, 1, 2 }, toggleArmament },
};
```
And I keep getting error telling me that there are too many initializers. How to work it out?
|
typedefis used to declare an alias to a type. Since you have an actual member here, remove the innertypedef.
```
typedef struct _sequence_t
{
const int seq[3];
void (* callbackPtr)();
} sequence_t;
```
|
Seems most open source projects in C/C++ only provide the source code,i.e.nginx
Is this a convention that anyone interested in joining the developing team should figure out the.sln/.projectfiles himself to qualify??
|
most open source projects are coming from the linux side of computing. thus, they are mainly using unix style build tools, as well as open source compilers.
the main build tool ismake, which uses amakefileto know how to build a project. on Windows, the main open source compiler isMinGWwhich is a win32 port ofgcc. the use of those tools allows to keep a maximum of common things between unix and windows.
note that .sln files are specific to microsoft compilers which are not free to use (and are rather costly), they are not portable and so are not suitable for multi-platform programming.
|
I need to have an array of structs in a game I'm making - but I don't want to limit the array to a fixed size. I'm told there is a way to use realloc to make the array bigger when it needs to, but can't find any working examples of this.
Could someone please show me how to do this?
|
Start off by creating the array:
```
structName ** sarray = (structName **) malloc(0 * sizeof(structName *));
```
Always keep track of the size separately:
```
size_t sarray_len = 0;
```
To increase or truncate:
```
sarray = (structName **) realloc(sarray, (sarray_len + offset) * sizeof(structName *));
```
Then set the size:
```
sarray_len += offset;
```
Happy to help and hope that helps.
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
```
main()
{
int a=5;
a= a++ + ++a + ++a + a++ + a++;
printf("%d",a);
}
```
|
This is not defined.
You can find the Committee Draft from May 6, 2005 of the C-standardhere(pdf)
See section6.5 Expressions:
2 Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.
and the example:
71) This paragraph renders undefined statement expressions such asi = ++i + 1;a[i++] = i;
|
When you create a menu bar, a funny line appears underneath (for XP and Win7 at least). How can I get rid of this line? I know that some applications, such as Firefox and Thunderbird, have done so.
Here's an illustration:
I am programming in C, using the Windows API. My menu is loaded from a resource file.
|
I'd say that line is supposed to be there (Run a simple application like calc and see) If you look at an application like Explorer (Or IE4-6) in XP, its menu is actually a toolbar inside of a rebar.
If you look at a function like GetMenuBarInfo() you will see there is no border property you can query or set.
If a 1 pixel line is that important, you probably have to A) Do some owner drawing on the menu to paint over that line or B) Implement a custom menu control (MS even has atutorial for IE/Explorer style menus)
|
This question already has answers here:How to read a line from the console in C?(14 answers)Closed6 years ago.
I want to take a string from stdin but I don't want a static array of fixed size
I know that scanf need something where save the stdin input, but I can't do something like this:
```
char string[10]
scanf("%s",string);
```
becouse I need to know before how long will be the string in order to allocate the right memory space.
Can you help me to resolve this problem?
woooooooo
i'm still locked with this problem...
I'm going mad
can you please give me the working code?
|
The only way to be sure is to do a loop; read one character at a time and store. If your allocated buffer becomes full, grow it by some suitable amount (more than one byte at a time is recommended for performance, a classic rule-of-thumb is to double it).
Stop when you consider the string to end, perhaps at line feed or EOF.
|
Is there a portable C library to access .zip archives? "gzip" or "zlib" (the closest I could find) only handle compressed data, I need to be able to list the files inside the archive, and access each one individually, and if they're compressed using the 'deflate' method, I can use zlib on it.
|
Minizip, maybe?
http://www.winimage.com/zLibDll/minizip.html
|
As per subject.
I have some constants hash defined like so:
```
#define CONST 40
```
I've set a breakpoint in my program. How do I print the value of that constant? (I know I can just look at the source code, but I want to be sure of it)
|
```
help macro
```
You must compile with the -g3 flag for it to work and start your program before the macros are loaded.
In your case:
```
info macro CONST
```
or
```
macro expand CONST
```
More info:http://sourceware.org/gdb/current/onlinedocs/gdb/Macros.html
|
I was wondering if you knew of a robust implementation of a hashtable in C. I'm looking for something other than ghashtable in glib.
Thanks.
|
I've heard good things about theGLib Hash Table.
|
In this article :http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=/com.ibm.vacpp6m.doc/language/ref/clrc03defst.htm
What's means the sentence "In C, a structure member may be of any type except "function returning T" (for some type T)"
Thanks for all the answers!
|
In C there are no member functions - you can have pointers to functions as members, but you can't declare or define functions in structures:
```
struct X {
int f(); // illegal in C
int g() { return 42; } // same here
int (*h)(); // pointer to function, fine
};
```
|
I am developing a progress bar using Ajax. My client side code is working fine, but I have issue at server side. I am using C based CGI.
```
if(i == inc && pb_inc<=100)
{
fptr = fopen("progress_bar.txt", "w");
fprintf(fptr,"%d", j);
fclose(fptr);
pb_inc++;
}
```
basically I am increasing progress bar after certain number of bytes. What I see here is that the CGI doesn't let display any data to text file until it has sent all the data to file one by one.
i have referred tohttp://www.redips.net/javascript/ajax-progress-bar/
Any idea whats happening here?
|
Does callingfflush(fptr)improve things? I'm assuming the client side is requestingprogress_bar.txt, which may not be updating as you expect.
|
I'm wondering if there is an Objective C equivalent to .Net's BitConverter.GetBytes() method.
For example, in C#, I can write something like this:
byte[] lengthPrefix = BitConverter.GetBytes(message.length);
What would the equivalent be in Objective C?
Some example code would be greatly appreciated.
Thanks in advance.
|
If you don't need a specific endian-ness:
```
unsigned char * lengthPrefix = (unsigned char *)&message.length;
```
Or, copy to a 32-bit buffer, if needed.
```
unsigned char lengthPrefixBuffer[4];
memcpy(lengthPrefixBuffer, &message.length, 4);
```
|
I have written some C/C++ extension modules for PHP, using the 'old fashioned way' - i.e. by using the manual way (as described by Sarah Golemon in her book).
This is too fiddly for me, and since I am lazy, and would like to automate as much as possible. Also, I have used SWIG now to generate extensions to Python, and I am getting to like using it quite a lot.
I am thinking of using SWIG to generate my future PHP extensions. I am using PHP v5.2 (and above) on my production servers.
My questions are:
Is SWIG PHP interface stable yet (i.e. ready for production)?If you answered yes to question 1 -areYOUusing it inYOURproduction site?Are there any 'gotchas' I need to be aware of when creating PHP extension ,modules using SWIG?
|
I have extensively used SWIG in production environment for generating PHP wrappers. Its pretty stable and can be used without issues.
|
So I have some temp data in my program (in RAM). I want to somehow make it seem as it is a file (for example for sending it into another program which takes a file link as argument)?
Is it possible?
How to do such thing?
|
Why not simply write the file to disk? If writing to disk is too slow, you can pass theFILE_ATTRIBUTE_TEMPORARYflag toCreateFileto keep the data in cache (and avoid writing it to the physical device).
Sometimes the obvious solutions are the best...
|
I need to write a C program that will allow me to read/write files that are owned by root. However, I can only run the code under another user. I have the root password, but there are no "sudo" or "su" commands on the system, so I have no way of accessing the root account (there are practically no shell commands whatsoever, actually). I don't know a whole lot about UNIX permissions, so I don't know whether or not it is actually possible to do this without exploiting the system in some way or running a program owned by root itself (with +s or whatever). Any advice?
Thanks!
P.S. No, this isn't anything malicious, this is on an iPhone.
|
Under the UNIX permissions system, you need to run a file owned by root itself that's marked setuid-root (+s, as you said) or communicate with some process that is already running as root.
If there is no such file, you are out of luck.
|
Disclaimer, I not do anything in particular with regards this question, just curious.
Is it possible to take address of instruction or block in C? in essence, is there jump equivalent in C?
for example:
```
void function() {
int k;
{ // is a possible to go to this address from arbitrary point in code?
int i, j;
k += j+i;
}
}
```
thank you
|
I think the closest you can come using standard techniques issetjmpandlongjump. They won't get you access to the actual address though, because thejmp_bufobject is opaque.
|
In C++, if an object of a class is passed as a parameter into a function, the copy constructor of the class will be called.
I was wondering if the object is of nonclass type, what function will be called?
Similarly in C, what function is called when passing values or address of variables into a function?
Thanks and regards!
|
No function will be called; the bytes composing the object will simply be copied to the correct place for the callee (be that a location in memory or a register).
|
In a C struct I have defined a function pointer as follows:
```
typedef struct _sequence_t
{
const int seq[3];
typedef void (* callbackPtr)();
} sequence_t;
```
I want to initialize a var of that type globally with:
```
sequence_t sequences[] = {
{ { 0, 1, 2 }, toggleArmament },
};
```
And I keep getting error telling me that there are too many initializers. How to work it out?
|
typedefis used to declare an alias to a type. Since you have an actual member here, remove the innertypedef.
```
typedef struct _sequence_t
{
const int seq[3];
void (* callbackPtr)();
} sequence_t;
```
|
Seems most open source projects in C/C++ only provide the source code,i.e.nginx
Is this a convention that anyone interested in joining the developing team should figure out the.sln/.projectfiles himself to qualify??
|
most open source projects are coming from the linux side of computing. thus, they are mainly using unix style build tools, as well as open source compilers.
the main build tool ismake, which uses amakefileto know how to build a project. on Windows, the main open source compiler isMinGWwhich is a win32 port ofgcc. the use of those tools allows to keep a maximum of common things between unix and windows.
note that .sln files are specific to microsoft compilers which are not free to use (and are rather costly), they are not portable and so are not suitable for multi-platform programming.
|
I need to have an array of structs in a game I'm making - but I don't want to limit the array to a fixed size. I'm told there is a way to use realloc to make the array bigger when it needs to, but can't find any working examples of this.
Could someone please show me how to do this?
|
Start off by creating the array:
```
structName ** sarray = (structName **) malloc(0 * sizeof(structName *));
```
Always keep track of the size separately:
```
size_t sarray_len = 0;
```
To increase or truncate:
```
sarray = (structName **) realloc(sarray, (sarray_len + offset) * sizeof(structName *));
```
Then set the size:
```
sarray_len += offset;
```
Happy to help and hope that helps.
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
```
main()
{
int a=5;
a= a++ + ++a + ++a + a++ + a++;
printf("%d",a);
}
```
|
This is not defined.
You can find the Committee Draft from May 6, 2005 of the C-standardhere(pdf)
See section6.5 Expressions:
2 Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.
and the example:
71) This paragraph renders undefined statement expressions such asi = ++i + 1;a[i++] = i;
|
When you create a menu bar, a funny line appears underneath (for XP and Win7 at least). How can I get rid of this line? I know that some applications, such as Firefox and Thunderbird, have done so.
Here's an illustration:
I am programming in C, using the Windows API. My menu is loaded from a resource file.
|
I'd say that line is supposed to be there (Run a simple application like calc and see) If you look at an application like Explorer (Or IE4-6) in XP, its menu is actually a toolbar inside of a rebar.
If you look at a function like GetMenuBarInfo() you will see there is no border property you can query or set.
If a 1 pixel line is that important, you probably have to A) Do some owner drawing on the menu to paint over that line or B) Implement a custom menu control (MS even has atutorial for IE/Explorer style menus)
|
This question already has answers here:How to read a line from the console in C?(14 answers)Closed6 years ago.
I want to take a string from stdin but I don't want a static array of fixed size
I know that scanf need something where save the stdin input, but I can't do something like this:
```
char string[10]
scanf("%s",string);
```
becouse I need to know before how long will be the string in order to allocate the right memory space.
Can you help me to resolve this problem?
woooooooo
i'm still locked with this problem...
I'm going mad
can you please give me the working code?
|
The only way to be sure is to do a loop; read one character at a time and store. If your allocated buffer becomes full, grow it by some suitable amount (more than one byte at a time is recommended for performance, a classic rule-of-thumb is to double it).
Stop when you consider the string to end, perhaps at line feed or EOF.
|
Is there a portable C library to access .zip archives? "gzip" or "zlib" (the closest I could find) only handle compressed data, I need to be able to list the files inside the archive, and access each one individually, and if they're compressed using the 'deflate' method, I can use zlib on it.
|
Minizip, maybe?
http://www.winimage.com/zLibDll/minizip.html
|
As per subject.
I have some constants hash defined like so:
```
#define CONST 40
```
I've set a breakpoint in my program. How do I print the value of that constant? (I know I can just look at the source code, but I want to be sure of it)
|
```
help macro
```
You must compile with the -g3 flag for it to work and start your program before the macros are loaded.
In your case:
```
info macro CONST
```
or
```
macro expand CONST
```
More info:http://sourceware.org/gdb/current/onlinedocs/gdb/Macros.html
|
I was wondering if you knew of a robust implementation of a hashtable in C. I'm looking for something other than ghashtable in glib.
Thanks.
|
I've heard good things about theGLib Hash Table.
|
In this article :http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=/com.ibm.vacpp6m.doc/language/ref/clrc03defst.htm
What's means the sentence "In C, a structure member may be of any type except "function returning T" (for some type T)"
Thanks for all the answers!
|
In C there are no member functions - you can have pointers to functions as members, but you can't declare or define functions in structures:
```
struct X {
int f(); // illegal in C
int g() { return 42; } // same here
int (*h)(); // pointer to function, fine
};
```
|
I am developing a progress bar using Ajax. My client side code is working fine, but I have issue at server side. I am using C based CGI.
```
if(i == inc && pb_inc<=100)
{
fptr = fopen("progress_bar.txt", "w");
fprintf(fptr,"%d", j);
fclose(fptr);
pb_inc++;
}
```
basically I am increasing progress bar after certain number of bytes. What I see here is that the CGI doesn't let display any data to text file until it has sent all the data to file one by one.
i have referred tohttp://www.redips.net/javascript/ajax-progress-bar/
Any idea whats happening here?
|
Does callingfflush(fptr)improve things? I'm assuming the client side is requestingprogress_bar.txt, which may not be updating as you expect.
|
I'm wondering if there is an Objective C equivalent to .Net's BitConverter.GetBytes() method.
For example, in C#, I can write something like this:
byte[] lengthPrefix = BitConverter.GetBytes(message.length);
What would the equivalent be in Objective C?
Some example code would be greatly appreciated.
Thanks in advance.
|
If you don't need a specific endian-ness:
```
unsigned char * lengthPrefix = (unsigned char *)&message.length;
```
Or, copy to a 32-bit buffer, if needed.
```
unsigned char lengthPrefixBuffer[4];
memcpy(lengthPrefixBuffer, &message.length, 4);
```
|
does ansi c allows serial communication on rs232 null modem?
if yes then any one give me example?
thanx in advance
|
Ansi C has nothing to do with serial communications. ANSI C is a formal description of the C language, it doesn't define libraries. Communicating with an RS-232 modem is possible with C language, but it will be completely different in different platforms (Windows, Linux, embedded processors).
|
I have a file of data Dump, in with different timestamped data available, I get the time from timestamp and sleep my c thread for that time. But the problem is that The actual time difference is 10 second and the data which I receive at the receiving end is almost 14, 15 second delay. I am using window OS. Kindly guide me.
Sorry for my week English.
|
The sleep function will sleep for at least as long as the time you specify, but there is no guarantee that it won't sleep for longer.If you need an accurate interval, you will need to use some other mechanism.
|
I need to know if there is an iPhone C compiler that can be installed on the iPhone. Then I would like to know what parameter I would put in thesystem("compile Foo")function. Thanks for the help in advanced.
|
Unfortunately for your purposes, an app store app is not permitted to launch another process, which would mean that you couldn't use another compiler even if you could install one on the phone.
|
The way being suppose the data is
123 134 2312 32131 2131231 211212
It should take them as different numbers and store them in an integer array .
|
You can usefscanfwith%dformat specifier to read successive integer values from a text file.
|
i am using Win32 API.
i have a thread in c and want to terminate it from out side the thread so can't use exitthread()
i can't use any wait options cause i have to kill this thread and start it again in very short time.
need help,
|
You can thermiate the thread using TerminateThread using the thread handle you got from CreateThread.
seehttp://msdn.microsoft.com/en-us/library/ms686717(VS.85).aspx
Please note the warning in the MSDN site. Terminating a thread is dangerous.
Consider that the thread can have resources allocated, that will not released when you terminate it as you describe. Example: if the thread has entered a critical section and is terminated before leaving, you won't be able to enter the CS with another thread.
|
Does Windows provide some sort of evented API so I can run some code whenever a drive (say a usb stick) is attached?Similar to howReadDirectoryChangesWis for events on the filesystem?I am not interested only in hardware changes, a user can also mount a volume, a ftp drive or similar.
|
I am not sure of the API, but you can handle theWM_DEVICECHANGEmessage.
|
Can any body explains about the different categories of pointer(like wild pointers)?
|
Validpointer: one pointing to a real object in memoryInvalidpointer: one pointing to memory that is not what it is supposed to be.NULLpointer: A pointer whose value is 0 and thus points at nothing.Danglingpointer (also sometimes wild pointer): one pointing to memory that has been deleted/freed.Smartpointer: Not really a pointer at all, but rather an object which acts like a pointer, but manages the memory for you.
|
MY scenario is... I have 6,000 datas in Excel Sheet.. I try to import to Access Database.It enters the Database like this..
UNit Price 34512.00 Vat 4.00
BUt when i Retrieve to DataGridColumn it Shows vat Rate as 4(whole number).I accept zeros has no values..But I need that to be displayed in Grid as 4.0 . How to achieve this
|
Use a format string, here is some referenceStandard Numeric Format Stings
|
I was wondering how I can show description text. By this I mean, for example if you hover over the Start button a small description will appear saying "Start". How are these invoked?
Thanks
|
You are looking forTooltip Controls
|
I am currently upgrading our software to support ipv6 and in the meantime I'm expanding hostname/ip fields to the max hostname size. In sun documentation it seems like this can be up to 1025 (netdb.h:#define NI_MAXHOST 1025 - this is the recommended hostname allocation define), but when I pass a hostname of over 255 to getaddrinfo I get "getaddrinfo failed: memory allocation failure". I am testing on a Sol10 box. Ideas?
|
NI_MAXHOST is for getnameinfo(), getaddrinfo() uses the MAXHOSTNAMELEN. (seehere) , and that seems pretty much to be hardcoded - and there's little you can do about it.
Exactly why these differ I don't know, but see e.g. alsohere/herefor some info on max host name lengths.
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:How do I call unmanaged C/C++ code from a C# ASP.NET webpage
is there a way to link the two?
|
P/Invokeis the approach you want
|
Why is dereferencing called dereferencing?
I'm just learning pointers properly, and I'd like to know why dereferencing is called that. It confused me as it sounds like you are removing a reference, rather than going via the pointer to the destination.
Can anyone explain why it is called this?
To me something like destination or pointed_to_value would make more sense.
|
A pointerrefersto an object. Ergo, wedereferencethe pointer (or, get the referent of the pointer) to get the object pointed-to.
Thede-prefix most likely comes from the Latin preposition meaningfrom; I suppose you could think ofdereferenceas meaning "to obtain the referent (or object)from the reference."
|
Is there a way of converting a char into a string in C?
I'm trying to do so like this:
```
char *array;
array[0] = '1';
int x = atoi(array);
printf("%d",x);
```
|
```
char c = '1';
int x = c - '0';
printf("%d",x);
```
|
I am writing an eclipse plug-in which will operate in a mode in which it will need to send "commands" to another C program. The C program has a built-in poller which checks for events. The plug-in will "push" commands out but doesn't need anything in response. What's the easiest way to set up a communication mechanism between these two? I was thinking about using a read-only fifo on the C side which I would check from the poller, but I'm not sure how to coordinate the reading and writing between the two processes. Does one of the processes need to block while the other is accessing it? If so, how do I coordinate this? Anyone know of any samples out there? I haven't quite turned up exactly what I am looking for in my searches.
|
The simplest is probably just communicating over a socket connection, which allows you to use any network communication library for moving the actual bytes.
|
I'm making a drawing application with WINAPI and OpenGL. To make things more efficient I only redraw the region needed so I invalidateRect(hwnd,myRect,false).
I know OpenGL does self clipping but I want to do that for my rect. I want it to clip itself for the region I invalidated to make things even more efficient. Thanks
|
If I understood correctly, what you want is the scissor test. Enable it withglEnable(GL_SCISSOR_TEST);and set the scissor rectangle withglScissor(x, y, width, height);
|
I'm having a code written in C that works on Linux. I want this program to work in windows, Are there any differences that I have to make in the code ?
It is a code for Server/Client communication using sockets taken from here :http://www.linuxhowtos.org/C_C++/socket.htm
|
You can compile your code underCygwinorMINGW, both of which provide a certain degree of Linux-system-call-to-Windows-system-call-mapping, and you may avoid having to rewrite anything at all.
|
i need a real time clock in ansi c which provide an accuracy upto miliseconds?
i am working on windows a windows base lib is also acceptable thanx in advance.
|
You can't do it with portable code prior to C11.
Starting with C11, you can usetimespec_get, which willoften(but doesn't necessarily) provide a resolution of milliseconds or better. Starting from C23, you can calltimespec_getresto find out the resolution provided.
Since you're using Windows, you need to start out aware that Windows isn't a real-time system, so nothing you do is really guaranteed to be accurate. That said, you can start withtimeBeginPeriod(1);to set the multimedia timer resolution to 1 millisecond. You can then calltimeGetTime()to retrieve the current time with 1 ms resolution. When you're done doing timing, you calltimeEndPeriod(1)to set the timer resolution back to the default.
|
I'm trying to get better at C++ (I know a little). I'm working on character arrays. I found an exercise where the objective is to reverse a character array (after I convert it from an integer). I'm getting the following error (using VS2005):
Run-Time Check Failure #2 - Stack around the variable 'revBuffer' was corrupted.
When I step through the code, I notice the following:
revBuffer = 0x0012fe40 "100899ÌÌÌÌÌÌÌÌÌÌ998001"
The relevant code is below.
```
char buffer[5];
char revBuffer[5];
int i;
int j=5;
long number = 998001;
itoa(number, buffer, 10);
for(i=0; i<strlen(buffer);i++)
{
revBuffer[j] = buffer[i];
j--;
}
```
Any help would be great. TIA!
|
You are overindexing revBuffer. It is size 5, which means you can index it from 0 to 4, but the first index you use in it in your loop is 5.
|
In C++, what's the benefit of having a class with functions...
say
```
class someClass{
public:
void someFunc(int arg1);
};
```
then having the function's actual functionality declared after int main
```
int main()
{ return 0; }
void someClass::someFunc(int arg1)
{ cout<<arg1; }
```
Furthermore, what's the benefit of declaring the class in a .h header file, then putting the functionality in a .cpp file that #includes the .h file?
|
Dependency management. Users of the class only need to include the header file, so they don't depend on the implementation.
Another use is breaking circular dependencies.
Both issues may look like a waste of time with toy programs, but they start to grow into a really bad problem as the program grows.
|
I'm making a bigCproject and I have never come across a situation like this before so, I need your advice.
What is your opinion? Is it okay to have the constants defined within conditional preprocessors like I have done below or you advise me to do this some other way?
```
#define NUM_OCTAVES_4
//#define NUM_OCTAVES_5
#ifdef NUM_OCTAVES_4
#define OCTAVES 4
const unsigned char borders [4] = {11, 26, 50, 98};
#elif NUM_OCTAVES_5
#define OCTAVES 5
const unsigned char borders [5] = {11, 26, 50, 98, 194};
#endif
```
Any drawbacks if I do it this way?
|
```
#define OCTAVES 4
#if OCTAVES == 4
const unsigned char borders [4] = {11, 26, 50, 98};
#elif OCTAVES == 5
const unsigned char borders [5] = {11, 26, 50, 98, 194};
#endif
```
|
I was wondering how I can show description text. By this I mean, for example if you hover over the Start button a small description will appear saying "Start". How are these invoked?
Thanks
|
You are looking forTooltip Controls
|
I am currently upgrading our software to support ipv6 and in the meantime I'm expanding hostname/ip fields to the max hostname size. In sun documentation it seems like this can be up to 1025 (netdb.h:#define NI_MAXHOST 1025 - this is the recommended hostname allocation define), but when I pass a hostname of over 255 to getaddrinfo I get "getaddrinfo failed: memory allocation failure". I am testing on a Sol10 box. Ideas?
|
NI_MAXHOST is for getnameinfo(), getaddrinfo() uses the MAXHOSTNAMELEN. (seehere) , and that seems pretty much to be hardcoded - and there's little you can do about it.
Exactly why these differ I don't know, but see e.g. alsohere/herefor some info on max host name lengths.
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:How do I call unmanaged C/C++ code from a C# ASP.NET webpage
is there a way to link the two?
|
P/Invokeis the approach you want
|
Why is dereferencing called dereferencing?
I'm just learning pointers properly, and I'd like to know why dereferencing is called that. It confused me as it sounds like you are removing a reference, rather than going via the pointer to the destination.
Can anyone explain why it is called this?
To me something like destination or pointed_to_value would make more sense.
|
A pointerrefersto an object. Ergo, wedereferencethe pointer (or, get the referent of the pointer) to get the object pointed-to.
Thede-prefix most likely comes from the Latin preposition meaningfrom; I suppose you could think ofdereferenceas meaning "to obtain the referent (or object)from the reference."
|
Is there a way of converting a char into a string in C?
I'm trying to do so like this:
```
char *array;
array[0] = '1';
int x = atoi(array);
printf("%d",x);
```
|
```
char c = '1';
int x = c - '0';
printf("%d",x);
```
|
I am writing an eclipse plug-in which will operate in a mode in which it will need to send "commands" to another C program. The C program has a built-in poller which checks for events. The plug-in will "push" commands out but doesn't need anything in response. What's the easiest way to set up a communication mechanism between these two? I was thinking about using a read-only fifo on the C side which I would check from the poller, but I'm not sure how to coordinate the reading and writing between the two processes. Does one of the processes need to block while the other is accessing it? If so, how do I coordinate this? Anyone know of any samples out there? I haven't quite turned up exactly what I am looking for in my searches.
|
The simplest is probably just communicating over a socket connection, which allows you to use any network communication library for moving the actual bytes.
|
I'm making a drawing application with WINAPI and OpenGL. To make things more efficient I only redraw the region needed so I invalidateRect(hwnd,myRect,false).
I know OpenGL does self clipping but I want to do that for my rect. I want it to clip itself for the region I invalidated to make things even more efficient. Thanks
|
If I understood correctly, what you want is the scissor test. Enable it withglEnable(GL_SCISSOR_TEST);and set the scissor rectangle withglScissor(x, y, width, height);
|
I'm having a code written in C that works on Linux. I want this program to work in windows, Are there any differences that I have to make in the code ?
It is a code for Server/Client communication using sockets taken from here :http://www.linuxhowtos.org/C_C++/socket.htm
|
You can compile your code underCygwinorMINGW, both of which provide a certain degree of Linux-system-call-to-Windows-system-call-mapping, and you may avoid having to rewrite anything at all.
|
i need a real time clock in ansi c which provide an accuracy upto miliseconds?
i am working on windows a windows base lib is also acceptable thanx in advance.
|
You can't do it with portable code prior to C11.
Starting with C11, you can usetimespec_get, which willoften(but doesn't necessarily) provide a resolution of milliseconds or better. Starting from C23, you can calltimespec_getresto find out the resolution provided.
Since you're using Windows, you need to start out aware that Windows isn't a real-time system, so nothing you do is really guaranteed to be accurate. That said, you can start withtimeBeginPeriod(1);to set the multimedia timer resolution to 1 millisecond. You can then calltimeGetTime()to retrieve the current time with 1 ms resolution. When you're done doing timing, you calltimeEndPeriod(1)to set the timer resolution back to the default.
|
I'm trying to get better at C++ (I know a little). I'm working on character arrays. I found an exercise where the objective is to reverse a character array (after I convert it from an integer). I'm getting the following error (using VS2005):
Run-Time Check Failure #2 - Stack around the variable 'revBuffer' was corrupted.
When I step through the code, I notice the following:
revBuffer = 0x0012fe40 "100899ÌÌÌÌÌÌÌÌÌÌ998001"
The relevant code is below.
```
char buffer[5];
char revBuffer[5];
int i;
int j=5;
long number = 998001;
itoa(number, buffer, 10);
for(i=0; i<strlen(buffer);i++)
{
revBuffer[j] = buffer[i];
j--;
}
```
Any help would be great. TIA!
|
You are overindexing revBuffer. It is size 5, which means you can index it from 0 to 4, but the first index you use in it in your loop is 5.
|
In C++, what's the benefit of having a class with functions...
say
```
class someClass{
public:
void someFunc(int arg1);
};
```
then having the function's actual functionality declared after int main
```
int main()
{ return 0; }
void someClass::someFunc(int arg1)
{ cout<<arg1; }
```
Furthermore, what's the benefit of declaring the class in a .h header file, then putting the functionality in a .cpp file that #includes the .h file?
|
Dependency management. Users of the class only need to include the header file, so they don't depend on the implementation.
Another use is breaking circular dependencies.
Both issues may look like a waste of time with toy programs, but they start to grow into a really bad problem as the program grows.
|
I'm making a bigCproject and I have never come across a situation like this before so, I need your advice.
What is your opinion? Is it okay to have the constants defined within conditional preprocessors like I have done below or you advise me to do this some other way?
```
#define NUM_OCTAVES_4
//#define NUM_OCTAVES_5
#ifdef NUM_OCTAVES_4
#define OCTAVES 4
const unsigned char borders [4] = {11, 26, 50, 98};
#elif NUM_OCTAVES_5
#define OCTAVES 5
const unsigned char borders [5] = {11, 26, 50, 98, 194};
#endif
```
Any drawbacks if I do it this way?
|
```
#define OCTAVES 4
#if OCTAVES == 4
const unsigned char borders [4] = {11, 26, 50, 98};
#elif OCTAVES == 5
const unsigned char borders [5] = {11, 26, 50, 98, 194};
#endif
```
|
i am working on a project where i am using SysRc values as return values from some function like SUCCESS and FAILURE ond sum enums .
Now i want to know how to get them print?
|
Building on top of Neil's post:
A switch statement is usually the way to go with enum values in C++. You could save some writing work by using#define-macros, but I personally avoid them.
```
enum E { foo, bar };
const char * ToStr( E e ) {
switch(e) {
case foo: return "foo";
case bar: return "bar";
};
throw std::runtime_error("unhandled enum-value"); // xxx
}
```
gcc will warn you about unhandled case values.
|
Content ofX.c:
```
int i;
main ()
{
fun ();
}
```
Content ofY.c:
```
int i;
fun ()
{
}
```
Why does these two files compile with no error ? (using GCC)
But if i useint i = 10;it prints a multiple definition error.
|
You may be interested in this question and the answers. Keywords: "tentative definition".
Tentative definitions in C99 and linking
|
I wanted to know if that has any ill effects under any circumsatnce.
For ex:
```
Ex1:
void* func1()
{
void* p_ref = NULL;
//function scope static variable
static int var1 = 2;
p_ref = &var1;
return p_ref;
}
Ex2:
//file scope static variable
static int var2 = 2;
void* func2()
{
void* p_ref = NULL;
var2 = 3;
p_ref = &var2;
return p_ref;
}
```
So in the above two cases what is the difference apart from the fact that var1 is function scope and var2 is file scope.
Thanks in advance.
|
I don't believe there is any difference. They're both global variables, it's just that the name of the first one is only visible inside the scope of the function func1.
|
To define constants, what is the more common and correct way? What is the cost, in terms of compilation, linking, etc., of defining constants with #define? It is another way less expensive?
|
The best way to define any const is to write
```
const int m = 7;
const float pi = 3.1415926f;
const char x = 'F';
```
Using#defineis a bad c++ style. It is impossible to hide#definein namespace scope.
Compare
```
#define pi 3.1415926
```
with
```
namespace myscope {
const float pi = 3.1415926f;
}
```
Second way is obviously better.
|
I'm trying to implement a simple priority queue from array of queues. I'm trying to define a struct queue, and than a struct priority queue that has an array of queues as its member variable. However, when I try to compile the code, I get the following error:
pcb.h:30: error: array type has incomplete element type
The code is below:
```
typedef struct{
pcb *head;
pcb *tail;
SINT32 size;
} pcb_Q;
typedef struct {
struct pcb_Q queues[5];
SINT32 size;
} pcb_pQ;
```
Could someone give me a hand? Thanks a lot.
|
You already typedef the pcb_Q, no need to use struct keyword any more.
Just use this:
```
typedef struct {
pcb_Q queues[5];
SINT32 size;
} pcb_pQ;
```
|
I need to get last four bytes out of a double variable .The platform is Arm and compiler is RVCT.Programming language used is C.What is the safest way.
Thanks
|
```
int lastFour = *(((char*) &origDouble) + sizeof(double) - 4)
```
|
I have a set of characters, minimum hundreds of characters. How could i get the position of a particular character in that list efficiently.
|
If you set of characters is sorted, you can usebsearch().
If not, you're pretty much out of luck - you'll have to use a simple scan, likestrchr().
|
What does it mean when an object has two asterisks at the beginning?
```
**variable
```
|
In a declaration, it means it's a pointer to a pointer:
```
int **x; // declare x as a pointer to a pointer to an int
```
When using it, it deferences it twice:
```
int x = 1;
int *y = &x; // declare y as a pointer to x
int **z = &y; // declare z as a pointer to y
**z = 2; // sets the thing pointed to (the thing pointed to by z) to 2
// i.e., sets x to 2
```
|
I am trying to convert a string (const char* argv[]) to adoubleprecision floating point number:
```
int main(const int argc, const char *argv[]) {
int i;
double numbers[argc - 1];
for(i = 1; i < argc; i += 1) {
/* -- Convert each argv into a double and put it in `number` */
}
/* ... */
return 0;
}
```
Can anyone help me? Thanks
|
Usesscanf(Ref)
```
sscanf(argv[i], "%lf", numbers+i);
```
orstrtod(Ref)
```
numbers[i] = strtod(argv[i], NULL);
```
BTW,
```
for(i = 1; i < argc, i += 1) {
//-----------------^ should be a semicolon (;)
```
-->
|
I have this piece of code and i don't know how it works
```
#include <stdio.h>
int main(void)
{
int numero = ({const int i = 10; i+10;});
printf("%d\n", numero); // Prints 20
return 0;
}
```
Why if i delete the second part (i+10;), the compiler gets an error?
Why are the brackets necessary?
Thank you ^^!
|
It's aGCC statement expression. It executes the statements in it, and returns the value evaluated in the last statement. Thusnumerois initialized to20. If you delete the second part, there is no expression as the last statement, so it can't get a value from the statement expression.
The braces are necessary to disambiguate it from ordinary C parenthesized expressions.
|
The Size of pointer depends on the arch of the machine.
So
sizeof(int*)=sizeof(int) or sizeof(int*)=sizeof(long int)
I want to have a custom data type which is either int or long int depending on the size of pointer.
I tried to use macro #if, but the condition for macros does not allow sizeof operator.
Also when using if-else, typedef is limited to the scope of if.
```
if((sizeof(int)==sizeof(int *)){
typedef int ptrtype;
}
else{
typedef long int ptrtype;
}
//ptrtype not avialble here
```
Is there any way to define ptrtype globally?
|
In C99 you can useintptr_t.
|
I am programming in C, using the Windows API, and would like to know how I could drawseparators. I would appreciate a code example.
Edit: Here's an illustration.
(source:microsoft.com)
|
Use a static control/window with theSS_ETCHEDHORZstyle (This is what explorer does and should give you the most accurate rendering when it comes to Visual Styles)
|
I'm writing a mobile phone based game in c. I'm interested in a data structure that supports fast (amortized O(1) if possible) insertion, look-up, and removal. The data structure will store integers from the domain [0, n] where n is known ahead of time (it's a constant) and n is relatively small (on the order of 100000).
So far I've considered an array of integers where the "ith" bit is set iff the "ith" integer is contained in the set (so a[0] is integers 0 through 31, a[1] is integers 32 through 63 etc).
Is there an easier way to do this in c?
|
Your idea is simple and efficient - assuming you have 100000 / 8 = 12.5 KB to play with then I don't see any point in looking for other solutions.
|
I need to execute a file when I only know the descriptor. It is also possible that there are no links to the file so finding out the name somehow is not an option. All the execve(), execvp(), etc functions take a file name. dlopen() also takes a name.
Ugly solutions (like reading the file and calling some function pointer) are OK.
|
Usefexecve.
PS: reading the file and calling some function pointer is definitelynotOK. :)
|
I was wondering if I can usea library-written in C++- inC#The problem is that library has its own structures and classes..
Will I be able to use it in C#?
Thanks
EDITThis library is open source..so if my requirements needs something special in C++ code, I will be able do it...
|
You cannot directly use C++ classes in managed code. The chief problems are not being able to use the same memory allocator as used by the C++ code and not being able to invoke the constructor and destructor easily. A Microsoft employee posteda blog postto show that it is not impossible. I would not recommend doing this.
COM is a solution but that invariably requires a fairly big rewrite and good COM programming skillz. Amanaged class wrapperin the C++/CLI language is usually the best solution. You could take a peek at theSWIG toolto consider auto-generating those wrapper classes. Beware however that this tool can easily create more problems than it solves.
|
can I do something like this on Assemblybne jsr swap, if not how can I solve this problem from C, thanks in advance
```
if(start!=pivot_index){
swap(board,start,pivot_index);
}
```
I was taught that I must writejsrandsub-routinebut can I do something like thisbne sub-routine
|
In assembly that would usually be translated into something like this (pseudo-assembly):
```
load [start]
compare [pivot_index]
branch-if-equal label1
push [pivot_index]
push [start]
push [board]
call swap
add-stack-pointer 12
label1:
```
ie. theifstatement is converted into a jump that jumps over the body of theifif the controlling expression is not true.
|
I want to use cairo to enhance gtkentry look. For this, I have connected a callback to 'expose-event'. In callback, I call gtkentry's original expose-event handler. After that, I create cairo context and draw some lines and destroy the cairo. I return 'TRUE' as return value of callback function so that expose-event does not propagate.
Now my problem is, I am drawing line from (0,0) to (100,100). But line appears only over the border areas of the gtkentry. The place where text is, it does not appear.
Please help.
Kind Regards
-Durgesh O Mishra
|
GtkEntryuses an additionalGdkWindowfor the text area. It is sort-of-private, but you could access it using the following code:
```
GDK_WINDOW (gdk_window_peek_children (GTK_WIDGET (entry)->window)->data);
```
So, you can pass this window togdk_cairo_create().
If you have problems applying this to your code, paste the code — it's hard to guess what to do without having any way to test.
|
Having a string of whitespaces:
```
string *str = new string();
str->resize(width,' ');
```
I'd like to
fill length chars at a position.
In C it would look like
```
memset(&str[pos],'#', length );
```
How can i achieve this with c++ string, I tried
```
string& assign( const string& str, size_type index, size_type len );
```
but this seems to truncat the original string.
Is there an easy C++ way to do this?
Thanks.
|
In addition tostring::replace()you can usestd::fill:
```
std::fill(str->begin()+pos, str->begin()+pos+length, '#');
//or:
std::fill_n(str->begin()+pos, length, '#');
```
If you try to fill past the end of the string though, it will be ignored.
|
Lets say I have an array like
```
int arr[10][10];
```
Now i want to initialize all elements of this array to 0. How can I do this without loops or specifying each element?
Please note that this question if for C
|
The quick-n-dirty solution:
```
int arr[10][10] = { 0 };
```
If you initialiseanyelement of the array, C will default-initialise any element that you don't explicitly specify. So the above code initialises the first element to zero, and C sets all the other elements to zero.
|
I would really like to actually only allocate 64KB of memory, not 128KB and then do the alignment manually - far too wasteful. VirtualAlloc on windows gives precisely this behavior. Supposedly there's code in SquirrelFish for doing this on just about every platform, but I haven't managed to locate it. Is there a space efficient way to allocate 64KB on a 64KB boundary in POSIX? Failing that, in Linux?
|
Check outposix_memalign(3)
SYNOPSIS#include <stdlib.h>
int
posix_memalign(void **memptr, size_t alignment, size_t size);DESCRIPTIONThe posix_memalign() function allocates size bytes of memory such that
the allocation's base address is an exact multiple of alignment, and
returns the allocation in the value pointed to by memptr.
Check out the manpage for further details...
|
I've written a smalloperating system for embedded projectrunning on small to medium target.
I added some automated unit test with a high test code coverage (>95%), but the scope is only the static part.I got some code metrics as complexity and readability.I'm testing my code with a rule checker with MiSRA support, and of course fixed all warnings.I'm testing the code with a static analyzer and again fixed all warnings.
What can I do now totest - and improve - the reliability of my OS ?How about the dynamic part ?
|
Things missing in your list:
If you are not already doing it then also run the unit tests on the target hardware, to check for compiler and hardware issues.Code reviews, check especially for race conditions
You could also review the generated assembly code, if it is not too big.
|
Given a array of random integers, sort the odd elements in descending order and even numbers in ascending order.
Example input:(1,4,5,2,3,6,7)Output:(7,5,3,1,2,4,6)
Optimize for time complexity.
|
Which language is it, C or C++ (I see both tags)
In C++, you can usestd::sort()with appropriate ordering function. In C,qsort()works similarly:
```
#include <iostream>
#include <algorithm>
bool Order(int a, int b)
{
if (a%2 != b%2) return a%2;
else return a%2 ? b<a : a<b;
}
int main()
{
int a[] = {1,4,5,2,3,6,7};
size_t N = sizeof(a) / sizeof(a[0]);
std::sort(a, a+N, Order);
for(size_t i=0; i<N; ++i)
std::cout << a[i] << ' ';
std::cout << std::endl;
}
```
|
I was wondering if there was a way to run a thread on a seperate core instead of just a thread on that core?
Thanks
|
If you create a thread, you have by default no control on which core it will run. The operation system's scheduling algorithm takes care of that, and is pretty good at its job. However, you can use theSetThreadAffinityWinAPI to specify the logical cores a thread is allowed to run on.
Don't do that unless you have very good reasons. Quoting MSDN:
Setting an affinity mask for a process or thread can result in threads receiving less processor time, as the system is restricted from running the threads on certain processors. In most cases, it is better to let the system select an available processor.
|
I am debugging some C code with gdb. My program has a variable of typempz_t * retval. If I run the command
```
print *retval
```
I get the output
```
$23 = {{
_mp_alloc = 6,
_mp_size = 5,
_mp_d = 0x1001008d0
}}
```
Is there anything else I can do to get more information about the value stored inretval?
|
Try these:
```
(gdb) set print object on
(gdb) set print pretty on
(gdb) ptype *retval
(gdb) print *retval
```
What else do you you want to know?
|
lets say I have this
```
char *something[] = {
"/bi",
"-c",
"5",
NULL,
NULL
};
```
but I want to declare it in hex, how would I do this; compiler keeps erroring out on me:
```
char *something[] = {
{0x2f,0x62,0x69},
{0x2d,0x63},
{0x35},
{0x00},
{0x00}
};
```
to add something else to this, is 0x00 ALWAYS null? does 0x00 always translate to NULL on systems where NULL is -1 for example?
|
You can use hexadecimal escape sequences within a string literal. For example:
```
char *something[] = {
"\x2f\x62\x69",
"\x2d\x63"
};
```
|
Is theO_LARGEFILEflag needed if all that I want to do is write a large file (O_WRONLY) or append to a large file (O_APPEND | O_WRONLY)?
From a thread that I read titled "Cannot write >2gb index file" on the CLucene-dev mailing list, it appears thatO_LARGEFILEmight be needed to write large files, but participants in that discussion are usingO_RDWR, notO_WRONLY, so I am not sure.
|
O_LARGEFILEshould never be used directly by applications. It's to be used internally by the 64-bit-offset-compatible version ofopenin libc when it makes the syscall to the kernel (Linux, or possibly another kernel with this 64-bit-offset-mode-is-a-second-class-citizen nonsense). Just make sure to always include-D_FILE_OFFSET_BITS=64in yourCFLAGSand you'll never have to worry about anything.
|
I was wondering how ex Photoshop and Expression Design render sub tools. These show up when for example you hold your mouse down on the fill tool, a sub menu comes up to your right with the fill and gradient tools. I'm just not sure how to go about this because this sub menu would essentially have to be an extension of my toolbar, but then it would find itself on my Frame control. How is this handled? Would it be a good idea to just paint on my frame? Thanks
|
I'm pretty sure that they are created asbona fidetransient windows much as the pop-upFilemenu and sub-menus are. I'd look at thesource of GTKor similar to see how precisely that is done.
Painting directly on the frame tends to make a window system unhappy.
|
can somebody please explain, I have a program on C, can I convert it to assembly? if yes, how?
|
If you use gcc you can dogcc -O2 -S -c foo.caccording tothispage to get the output assembly in a human readable form.
|
In GDK there's an object calledGdkRectanglethat is used to draw rectangles. Is there a similar object for ellipses?
|
No. Actually,GdkRectangleis not used todrawrectangles directly, it is merely used tospecifyrectangle position. For instance,gdk_draw_rectangle()doesn't even accept anyGdkRectangleargument. To draw an ellipse, you could usegdk_draw_arc().
Note that using GDK for drawing is quite outdated. You could use Cairo and functionscairo_rectangle()andcairo_arc()for this.
|
Basically, I callTrackMouseEventin myWM_CREATEthen I also called it again after aWM_MOUSELEAVEevent, but this freezes up my program.
Where should I be sticking it?
|
You need to callTrackMouseEventwhen the mouse enters your control, and not when it leaves your control.
You can callTrackMouseEventon theWM_MOUSEMOVEmessage. You don't need to callTrackMouseEventevery timeWM_MOUSEMOVEis fired, just once up until you get anotherWM_MOUSELEAVE. After you get aWM_MOUSELEAVEyou can set some flag so the next call toWM_MOUSEMOVEwill know to callTrackMouseEventagain.
Basically you can emulate a fictionalWM_MOUSEENTERby usingWM_MOUSEMOVEand also having that flag set.
|
I have a file descriptor that is open for reading which may be non-blocking. What I need to do is simply read all data until reaching EOF and write that data to a writable file descriptor. As the process that performs this copying is not "aware" of anything that is going on around it, I don't think that I can do something useful while waiting for data, and I don't want to use awhileloop (whileerrnois notEAGAIN) because I think that it would be wasteful. Is there a way to block or otherwise suspend execution of the copying process until data becomes available?
|
Your other answer simply unsetsO_NONBLOCK, which sets the file back to blocking. That's perfectly fine, if that works in your situation; but if not, you can useselect()to block until your non-blocking file descriptor is readable.
|
What does it mean when an object has two asterisks at the beginning?
```
**variable
```
|
In a declaration, it means it's a pointer to a pointer:
```
int **x; // declare x as a pointer to a pointer to an int
```
When using it, it deferences it twice:
```
int x = 1;
int *y = &x; // declare y as a pointer to x
int **z = &y; // declare z as a pointer to y
**z = 2; // sets the thing pointed to (the thing pointed to by z) to 2
// i.e., sets x to 2
```
|
I am trying to convert a string (const char* argv[]) to adoubleprecision floating point number:
```
int main(const int argc, const char *argv[]) {
int i;
double numbers[argc - 1];
for(i = 1; i < argc; i += 1) {
/* -- Convert each argv into a double and put it in `number` */
}
/* ... */
return 0;
}
```
Can anyone help me? Thanks
|
Usesscanf(Ref)
```
sscanf(argv[i], "%lf", numbers+i);
```
orstrtod(Ref)
```
numbers[i] = strtod(argv[i], NULL);
```
BTW,
```
for(i = 1; i < argc, i += 1) {
//-----------------^ should be a semicolon (;)
```
-->
|
I have this piece of code and i don't know how it works
```
#include <stdio.h>
int main(void)
{
int numero = ({const int i = 10; i+10;});
printf("%d\n", numero); // Prints 20
return 0;
}
```
Why if i delete the second part (i+10;), the compiler gets an error?
Why are the brackets necessary?
Thank you ^^!
|
It's aGCC statement expression. It executes the statements in it, and returns the value evaluated in the last statement. Thusnumerois initialized to20. If you delete the second part, there is no expression as the last statement, so it can't get a value from the statement expression.
The braces are necessary to disambiguate it from ordinary C parenthesized expressions.
|
The Size of pointer depends on the arch of the machine.
So
sizeof(int*)=sizeof(int) or sizeof(int*)=sizeof(long int)
I want to have a custom data type which is either int or long int depending on the size of pointer.
I tried to use macro #if, but the condition for macros does not allow sizeof operator.
Also when using if-else, typedef is limited to the scope of if.
```
if((sizeof(int)==sizeof(int *)){
typedef int ptrtype;
}
else{
typedef long int ptrtype;
}
//ptrtype not avialble here
```
Is there any way to define ptrtype globally?
|
In C99 you can useintptr_t.
|
I am programming in C, using the Windows API, and would like to know how I could drawseparators. I would appreciate a code example.
Edit: Here's an illustration.
(source:microsoft.com)
|
Use a static control/window with theSS_ETCHEDHORZstyle (This is what explorer does and should give you the most accurate rendering when it comes to Visual Styles)
|
I'm writing a mobile phone based game in c. I'm interested in a data structure that supports fast (amortized O(1) if possible) insertion, look-up, and removal. The data structure will store integers from the domain [0, n] where n is known ahead of time (it's a constant) and n is relatively small (on the order of 100000).
So far I've considered an array of integers where the "ith" bit is set iff the "ith" integer is contained in the set (so a[0] is integers 0 through 31, a[1] is integers 32 through 63 etc).
Is there an easier way to do this in c?
|
Your idea is simple and efficient - assuming you have 100000 / 8 = 12.5 KB to play with then I don't see any point in looking for other solutions.
|
I need to execute a file when I only know the descriptor. It is also possible that there are no links to the file so finding out the name somehow is not an option. All the execve(), execvp(), etc functions take a file name. dlopen() also takes a name.
Ugly solutions (like reading the file and calling some function pointer) are OK.
|
Usefexecve.
PS: reading the file and calling some function pointer is definitelynotOK. :)
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.