question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
After seeingthisanswer
I have this doubt.
In my project,
I have seen some extern variables declared and defined like below:
file1.h
```
extern int a;
```
file1.c
```
extern int a=10;
```
But in the link I mentioned it says that in the c file it should be defined like:
```
int a = 10;
```
Does addingexternkey wo... |
It does not change the meaning.externonly makes sense when youdeclarea variable.Defininga variable withexternis the same because all global variables that are not markedstaticare symbols visible to the linker by default.
Note that if you didn't want to initialise the variable, that is, not having the part= 10, the co... |
How to define local static variables (that keeps its value between function calls) that are not shared among different threads?
I am looking for an answer both in C and C++
|
on Windows using Windows API:TlsAlloc()/TlsSetValue()/TlsGetValue()
on Windows using compiler intrinsic: use_declspec(thread)
on Linux (other POSIX???) :get_thread_area()and related
|
I am having a problem scanning chars into an array. Every time I do it will skip the next scan and go to the next. I know what is happening because the input also adds '\n' to the input but I do not know how to remedy the cause of it. Here is some sample code:
```
char charray [MAX], ffs;
int inarray [MAX], i;
for ... |
You can do like this.
```
while((c = getchar()) != '\n')
{
putchar(c);
}
```
this may solve your problem. or you can go till EOF also.
|
I'm using therecvfunction in a loop to receive network data, but let's say I want to stop receiving data mid-loop. I could just break the loop, but this doesn't seem like a very clean way to stop receiving data.
So is there any way to cleanly stop receiving data, or is just breaking the loop ok? It's HTTP GET/POST re... |
Breaking out of the recv loop won't close the connection. All that happens is that you stop calling recv and therefore stop reading data from the socket. Data from the peer will still be arriving on your socket. If you want to cleanly shutdown then callcloseon the socket file descriptor.
|
I want to run a C program that draws a circle. The program is compiling with no error and it is running. After getting the values like radius from the user, I get the error like this :
BGI error: Graphics not initialized ( use "initgraph")
Even though in my source code I have added this line :
```
int gmode,gdrive=... |
Your path ininitgraphis wrong. Use"c:\\tc\bgi"instead.
|
I have this code in linux kernel:
```
#define task_cred_xxx(task, xxx)
({
__typeof__(((struct cred *)NULL)->xxx) ___val;
rcu_read_lock();
___val = __task_cred((task))->xxx;
rcu_... |
Correct. It will return___val. However, block expressions like these are a GNU extension and isn't actually part of the C standard.
http://www.toofishes.net/blog/gcc-compound-statement-expressions/
|
Whenever I useopenI get the permission denied error. But when I usefopenit opens the file fine. What is wrong with my code?
```
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
char *filename = "dataread.txt";
rec = open(filename ,O_WRONLY | O_CREAT | O_TRUNC,mode);
if(rec == -1)
{
perror("\nopen error 1:");... |
I added anint rec=0;var declaration and the necessary includes files and then compiled your code.
It runs with no errors as a normal user in my Fedora 15 laptop. Check the dir/file permissions you are running this on, the problems does not seem to be in the code.
|
What that declaration means in C ?
```
void help_me (char *, char *);
```
I'm newbie, but I know about pointers. Seems like this is something different ?
|
This declaration says thathelp_meis a function taking two pointers tochar(for example, two strings).
For a function prototype declaration the variable names are optional:void help_me (char *, char *);andvoid help_me (char * foo, char * bar);are equivalent.
|
Om mac OS 10.6.7, I am creating some files in the temp directory. After a while I start getting failure in open syscall and error returned is 24 which means disk full. I checked the disk space and still 80GB is available. Are there any restrictions or special quota on temporary directory? I used following flags to ope... |
Error 24 is EMFILE meaning too many open files.
|
Hi Im currently building an iPad app. I was using the memset() as below but every tine it runs I get a bad access error?
```
arrayPointer = malloc(sizeof(int) * size);
memset(arrayPointer, 0, sizeof(int)* size); //sets all the values in the array to 0
```
Cheers
|
You could usecalloc()it basically does the same asmalloc()but also sets all bits to 0 in the allocated memory. It is also suited well for array initializations. For your example:
```
arrayPointer = calloc(sizeof(int), size);
```
EDIT:You should consider inspecting the returned pointer.NULLwill be returned, when your... |
What is the difference betweenarray[i]++(increment outside brackets) andarray[i++](increment inside brackets), where the array is an intarray[10]?
|
```
int a[] = {1, 2, 3, 4, 5};
int i = 1; // Second index number of the array a[]
a[i]++;
printf("%d %d\n", i, a[i]);
a[i++];
printf("%d %d\n", i, a[i]);
```
Output
```
1 3
2 3
```
a[i]++increments the element at indexi, it doesn't incrementi. Anda[i++]incrementsi, not the element at indexi.
|
```
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
int x=0;
int y=0;
while (x<15)y++,x+=++y;
printf ("%i %i",x, y);
getchar ();
getchar ();
return 0;
}
```
I don't know why x is 20 and y is 8 at the end.
Please explain it step by step.
|
```
while (x<15)y++,x+=++y;
```
=>
```
while (x<15) {
y++;
x += ++y;
}
```
=>
```
while (x < 15) {
y += 2;
x += y;
}
```
So:
```
Before 1st iteration: x = 0, y = 0;
After 1st iteration: x = 2, y = 2;
After 2nd iteration: x = 6, y = 4;
After 3rd iteration: x = 12, y = 6;
After 4th iteration: x ... |
I've got a method signature:
```
void word_not(lc3_word_t *R, lc3_word_t *A)
```
I need to take the contents of *A and copy them into *R.
How do I do this?
I've tried assignment
*R = *A; but my compiler complains.
Any ideas?
|
```
memcpy(R, A, sizeof(lc3_word_t));
```
memcpycopies a specific number of bytes from A to R. This assumes that this makes sense for the structs of type lc3_word_t that R points to allocated space.
|
What is the difference betweenxmalloc()andmalloc()for memory allocation?Is there any pro of usingxmalloc()?
|
xmalloc()is a non-standard function that has the mottosucceed or die. If it fails to allocate memory, it will terminate your program and print an error message tostderr.
The allocation itself is no different; only the behaviour in the case that no memory could be allocated is different.
Usemalloc(), since it's more ... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:Get IP address of an interface on linux
How can I get the ip address from the device name (Example: eth0)?
|
DISCLAIMER:Your application SHOULD NOT depend on this kind of information. The application must see and use IP addresses ONLY. Ethernet devices are operating system plumbing. Keep in mind that you may have IP addresses not associated with any device, or devices with multiple IP addresses, multiple protocols (IPv4, IPv... |
How would I get my replace_char function to work properly?
The way that I am trying it in the function below returns segmentation faults using gcc in Ubuntu.
I have tried other ways, but each time I try to change the value, I get a fault.
```
int main (void)
{
char* string = "Hello World!";
printf ("%s\n", s... |
There is nothing wrong with yourreplace_charfunction. The problem is that you are trying to modify a string literal ("Hello World!") and that's undefined behavior. Try making a copy of the string instead, like this:
```
char string[] = "Hello World!";
```
|
In writing an ext2 driver for my hobby OS, I ran into a problem reading the inode table from a block group descriptor.
The third field of the block group descriptor is the block ID of the inode table for that group. In my case for the root directory of my file system this comes back as 64. The superblock is located a... |
The block IDs in the block group descriptor table are all absolute, so block ID 64 is going to be stored at LBA 128 and 129 in your case.
|
Say I create a polygon with thePolygonfunction, and i'd like it to accept input from the mouse (similar to a button).
How would I do that?
EDIT:Processing theWM_LBUTTONDOWNandWM_MOUSEMOVEmessages, I'm using this code to check if the mouse is in the area of the polygon:
```
if (LOWORD(lParam) < 375 && LOWORD(lParam)... |
Polygon()is a function that is used to draw to a device context. As such it cannot receive inupt. You need a windowed control to do that.
Handle the input in your window and use a hit test to check if you are inside the polygon.
|
In java when we take input from console we get a String, even if we want an integer as input we get a input in String format, then we covert it in integer format using several methods, like Integer.parseInt(). Where as C/C++ also take input from console but there we get integer values directly from console we does not... |
Check out java.util.Scanner, it might do what you need:
http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html
|
```
void DoSomeThing(CHAR parm[])
{
}
int main()
{
DoSomeThing(NULL);
}
```
Is the passing NULL for array parameter allowed in C/C++?
|
What you cannot do is pass an array by value. The signature of the function
```
void f( char array[] );
```
is transformed into:
```
void f( char *array );
```
and you can always pass NULL as argument to a function taking a pointer.
You can however pass an array by reference in C++, and in that case you will not ... |
I want to make a Window in Gtk (Gtk# to be specific, but GTK+ or any other binding will do, the functions are generally the same) without a caption. Kind of like Mozilla Firefox 4 and Google Chrome. I don't know what to call it, caption less or widget on caption? Any Help? Thanks
|
The term is 'decorated'.
In plain GTK+, this isgtk_window_set_decorated()and in GTK#, dothis.Decorated = false;in your forms constructor, that's all.
Note that decoration is not only the title bar but also the frame that allows for resizing. There is unfortunately no way to have a resizable but title-bar-less window... |
I have multiple threads reading same int variable.
and one thread is writing the value.
I don't care about the race condition.
only my concern is writing and reading int value at same time is memory safe ?
and it will not result in any application crash .
|
Yes, that should be all right. The only way I can envision that crashing is if one of the threads deallocates the memory backing that integer. For best results I would also make sure the integers are aligned atsizeof(int)boundaries. (Some CPUs cannot access integers at all without this alignment. Others provide we... |
I came across this following code:
```
#include<stdio.h>
#define d(x) x(#x[3])
int main(){
d(putchar);
}
```
Which printscas the output. I wonder what does the macro#define d(x) x(#x[3])does? In C language is there an operator like#? I can see this inside the macro body i.e herex(#x[3]). According to my normal eye i... |
The character '#' is a stringizer -- it turns a symbol into a string. The code becomes
putchar("putchar"[3]);
|
In a .h file I defined:
```
#define PAIR_TYPE(type1, type2)\
typedef struct { \ // added \ after edit
type1 first; \ // added \ after edit
type2 second; \ // added \ after edit
}; // added ; after edit
#define MAKE_PAIR(val1, val2) {val1, val2}
PAIR_TYP... |
You need more backslashes on the lines after '{'
```
#define PAIR_TYPE(type1, type2)\
typedef struct {\
type1 first;\
type2 second;\
}
```
|
Is there any way to use std::pair and std::make_pair in C? seems that they are applicable in C++.
As I used
```
#include "utility"
```
it says it can not find such file
thansk for any suggestion
|
It's C++-only. C has no templates, so you will have to roll your own with macros to emulate them to some extent, for example:
```
#define PAIR_TYPE(type1, type2)\
typedef struct {\
type1 first;\
type2 second;\
}
#define MAKE_PAIR(val1, val2) {val1, val2}
PAIR_TYPE(int, float) mypair;
mypair p... |
I study C. Digging in some C source code where I found that line. I have read about pointers, but I did not see such an example.
```
char *uppercase (char *s);
```
What that mean ?
|
It's a declaration of a function that takes a char pointer and returns a char pointer.
|
When writing characters to an array from a stream, is there a way to make the length of the array the exact number of characters if the size of the stream is unknown at compile? For example when reading text input into an array and the size of text can be any length.
|
Find the size of the file
```
fseek(fp, 0, SEEK_END);
size = ftell(fp);
/* Rewind. */
fseek(fp, 0, SEEK_SET);
```
Allocate the memory
```
char *buf = malloc(size);
```
|
On OS X, how can code in a dylib find the path it was loaded from, at runtime?
Coming from a Windows background, I'm used being able to callGetModuleFileName(dllHandle,...).
There existsNSGetExecutablePath()which will give me the path of the executable for the current process. Is there an equivalent to give me the c... |
Usedladdr(3). Given a memory address, dladdr() outputs a structure that has, amongst other data, the path of the library containing the address. For example, inside your library:
```
#include <stdio.h>
#include <dlfcn.h>
void test(void) {
Dl_info info;
if (dladdr(test, &info)) {
printf("Loaded from p... |
How to concatenate two strings (one of them is stored in a variable) inCusing preprocessors?
For example how to do this?
```
#define CONCAT(x,y) x y
//ecmd->argv[0] is equal to "sometext"
myfunc(CONCAT("/", ecmd->argv[0]), ecmd->argv[0]); //error: expected ')' before 'ecmd'
```
|
You can't concatenate them using a macro like that. using the preprocessor, only raw strings (either string literals or names) can be concatenated.
You have to usestrcator some other technique to combine the strings. For example:
```
char * buf = malloc(strlen(ecmd->argv[0]) + 2);
buf[0] = '/'; buf[1] = '\0';
strc... |
I am trying to pass on a list of arguments to sprintf which apparently doens't pick them up. What am i missing?
```
void respond( const char *format, ...) {
char buffer[256];
va_list args;
int len, retCode;
va_start( args, format);
len = sprintf( buffer, format, args);
va_end( args);
retCode = send( n... |
Usevsnprintf()instead sprintf().
http://pubs.opengroup.org/onlinepubs/009695399/functions/vprintf.html
|
This question already has answers here:How can use asm() with a const char* instead of a string literal?(1 answer)C/C++ inline assembler with instructions in string variables(2 answers)Closed2 years ago.
I did something like this :
char command [] = "Some assmebly code";asm volatile(command);
It didnt work. Specifi... |
As far as I know asm code fragment are inlined during compilation phase, not run-time. Which means you can't do what you are doing.
As pmg suggested, you could do it by calling external commands, but it would mean user would need to have all the tools installed.
|
I am programming with cuda in C. I got a segmentation fault with the code lines following:
```
int width = 0;
int height = 0;
// load input image
unsigned char * image_input = loadFile(&width, &height, "test.bmp");
// allocate memory for output
unsigned char * image_output = (unsigned char *) malloc(width*height*si... |
Size is sizeof(int) *H*W. (in bytes)Image_input is H*W. (in bytes)
You are addressing image_input beyond its size.
|
I am making a terminal software like GNU MC and I need gotoxy foo, but it has to be in C. It can be in macro or in C, but not in ASM code because I don`t know ASM. Any bit operators can be used too, but I had no idea how to pseudocode it or how to start doing this. Any advice will be most appreciated :)
|
Hope this snippet works with you.
I found these snippet on google long ago. I just saved it on my disk, now after seeing your post I just opened it.
Code
```
#include <stdio.h>
#include <stdlib.h>
void gotoxy(int x,int y)
{
printf("%c[%d;%df",0x1B,y,x);
}
int main(void)
{
gotoxy(10,10);
printf("hello ... |
I have multiple threads reading same int variable.
and one thread is writing the value.
I don't care about the race condition.
only my concern is writing and reading int value at same time is memory safe ?
and it will not result in any application crash .
|
Yes, that should be all right. The only way I can envision that crashing is if one of the threads deallocates the memory backing that integer. For best results I would also make sure the integers are aligned atsizeof(int)boundaries. (Some CPUs cannot access integers at all without this alignment. Others provide we... |
I came across this following code:
```
#include<stdio.h>
#define d(x) x(#x[3])
int main(){
d(putchar);
}
```
Which printscas the output. I wonder what does the macro#define d(x) x(#x[3])does? In C language is there an operator like#? I can see this inside the macro body i.e herex(#x[3]). According to my normal eye i... |
The character '#' is a stringizer -- it turns a symbol into a string. The code becomes
putchar("putchar"[3]);
|
In a .h file I defined:
```
#define PAIR_TYPE(type1, type2)\
typedef struct { \ // added \ after edit
type1 first; \ // added \ after edit
type2 second; \ // added \ after edit
}; // added ; after edit
#define MAKE_PAIR(val1, val2) {val1, val2}
PAIR_TYP... |
You need more backslashes on the lines after '{'
```
#define PAIR_TYPE(type1, type2)\
typedef struct {\
type1 first;\
type2 second;\
}
```
|
Is there any way to use std::pair and std::make_pair in C? seems that they are applicable in C++.
As I used
```
#include "utility"
```
it says it can not find such file
thansk for any suggestion
|
It's C++-only. C has no templates, so you will have to roll your own with macros to emulate them to some extent, for example:
```
#define PAIR_TYPE(type1, type2)\
typedef struct {\
type1 first;\
type2 second;\
}
#define MAKE_PAIR(val1, val2) {val1, val2}
PAIR_TYPE(int, float) mypair;
mypair p... |
I study C. Digging in some C source code where I found that line. I have read about pointers, but I did not see such an example.
```
char *uppercase (char *s);
```
What that mean ?
|
It's a declaration of a function that takes a char pointer and returns a char pointer.
|
When writing characters to an array from a stream, is there a way to make the length of the array the exact number of characters if the size of the stream is unknown at compile? For example when reading text input into an array and the size of text can be any length.
|
Find the size of the file
```
fseek(fp, 0, SEEK_END);
size = ftell(fp);
/* Rewind. */
fseek(fp, 0, SEEK_SET);
```
Allocate the memory
```
char *buf = malloc(size);
```
|
On OS X, how can code in a dylib find the path it was loaded from, at runtime?
Coming from a Windows background, I'm used being able to callGetModuleFileName(dllHandle,...).
There existsNSGetExecutablePath()which will give me the path of the executable for the current process. Is there an equivalent to give me the c... |
Usedladdr(3). Given a memory address, dladdr() outputs a structure that has, amongst other data, the path of the library containing the address. For example, inside your library:
```
#include <stdio.h>
#include <dlfcn.h>
void test(void) {
Dl_info info;
if (dladdr(test, &info)) {
printf("Loaded from p... |
How to concatenate two strings (one of them is stored in a variable) inCusing preprocessors?
For example how to do this?
```
#define CONCAT(x,y) x y
//ecmd->argv[0] is equal to "sometext"
myfunc(CONCAT("/", ecmd->argv[0]), ecmd->argv[0]); //error: expected ')' before 'ecmd'
```
|
You can't concatenate them using a macro like that. using the preprocessor, only raw strings (either string literals or names) can be concatenated.
You have to usestrcator some other technique to combine the strings. For example:
```
char * buf = malloc(strlen(ecmd->argv[0]) + 2);
buf[0] = '/'; buf[1] = '\0';
strc... |
I am trying to pass on a list of arguments to sprintf which apparently doens't pick them up. What am i missing?
```
void respond( const char *format, ...) {
char buffer[256];
va_list args;
int len, retCode;
va_start( args, format);
len = sprintf( buffer, format, args);
va_end( args);
retCode = send( n... |
Usevsnprintf()instead sprintf().
http://pubs.opengroup.org/onlinepubs/009695399/functions/vprintf.html
|
This question already has answers here:How can use asm() with a const char* instead of a string literal?(1 answer)C/C++ inline assembler with instructions in string variables(2 answers)Closed2 years ago.
I did something like this :
char command [] = "Some assmebly code";asm volatile(command);
It didnt work. Specifi... |
As far as I know asm code fragment are inlined during compilation phase, not run-time. Which means you can't do what you are doing.
As pmg suggested, you could do it by calling external commands, but it would mean user would need to have all the tools installed.
|
I am programming with cuda in C. I got a segmentation fault with the code lines following:
```
int width = 0;
int height = 0;
// load input image
unsigned char * image_input = loadFile(&width, &height, "test.bmp");
// allocate memory for output
unsigned char * image_output = (unsigned char *) malloc(width*height*si... |
Size is sizeof(int) *H*W. (in bytes)Image_input is H*W. (in bytes)
You are addressing image_input beyond its size.
|
I am making a terminal software like GNU MC and I need gotoxy foo, but it has to be in C. It can be in macro or in C, but not in ASM code because I don`t know ASM. Any bit operators can be used too, but I had no idea how to pseudocode it or how to start doing this. Any advice will be most appreciated :)
|
Hope this snippet works with you.
I found these snippet on google long ago. I just saved it on my disk, now after seeing your post I just opened it.
Code
```
#include <stdio.h>
#include <stdlib.h>
void gotoxy(int x,int y)
{
printf("%c[%d;%df",0x1B,y,x);
}
int main(void)
{
gotoxy(10,10);
printf("hello ... |
Look at the following two codes, and tell me the reason why answers vary a lot.
```
#include<stdio.h>
int main() {
float a = 0.9;
if(a<0.9)
printf("hi"); // This will be the answer
else
printf("bye");
return 0;
}
```
And if we change 0.9 to 0.8, then else's statement is printed:
```
... |
This error is due to floating point accuracy and because you are comparing afloattype with adoublevalue. Try to compare it versus floating point literals:if(a<0.8f)
I suggest you read the accordingwikipedia article, it explains in detail why your error happens.
|
I get "implicit declaration of function 'strncmp' isinvalid in C99" when use strncmp (xcode 4/ gcc version 4.2.1)
How to avoid this ?
|
From thestrncmp(3)man page:
#include <string.h>
|
What is the difference between using(char)0and'\0'to denote the terminating null character in a character array?
|
They're both a 0, but(char) 0is a char, while'\0'is (unintuitively) anint. This type difference should not usually affect your program if the value is 0.
I prefer'\0', since that is the constant intended for that.
|
For an online game I'm making, I need to be able to add users and their stats to a database, an example table:
Username, Password, Email, Wins, Loses
The username will be the unique key, and from there I need to retrieve the other information.
I also need to do other things such as find all the usernames with a giv... |
The SQLite documentation is quite good:
Documentation main pageQuickstartC/C++ API intro
|
I'm usingSetTimerto create a timer in my application with an interval of 50ms, this timer is going to be used to draw an object, and move it around.
Now I don't want the object to move when the window is out of focus, but I still need it to be painted.
And having it paint every 50ms, seems unnecessary. And performanc... |
When you get WM_ACTIVATE, decide whether to call KillTimer or SetTimer.
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.
I have a code and fromkladblok.txtt... |
The algorithm is very simple:
Open the fileAllocate a 2 dimensional array which is big enough to contain the numbersRead the numbers to the arrayClose the filePrint the array transposedFree the array
|
I'm using these window styles when callingCreateWindowWS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOXThis disables the maximize box, but is there any way I can completely remove it?
|
No easy way, but if you are going to draw the title bar yourself - in this case you can do it.
To give you an idea, this articleAdding a 'Minimize to tray'-button to a Form's caption barexplains how to add a button. Removing standard button is about the same - customization ofnon-client area.
|
In windows, when you click the small icon in the upper left of the window, you get a menu with Move, Minimize, Maximize, and Close options.
Is there anyway I can add my own options to that menu?
|
Absolutely.
GetSystemMenu(hWindow, FALSE)gets you menu handle and you are free to modify it.
A nice way is to add a separator and append your additional items like "About...". ATL code snippet is here:http://www.assembla.com/code/roatl-utilities/subversion/nodes/trunk/FilterGraphSpy/GraphBuilderCallbackPropertySheet... |
I do most of my programming on embedded processors, or on linux. When i need to sync data to my persistant store, i usually use the sync(2) system call. Is there an equivelent for Windows?
|
http://msdn.microsoft.com/en-us/library/aa364439(VS.85).aspxhttp://www.codeproject.com/KB/system/EjectMediaByLetter.aspx
FlushFileBuffers with a handle to a volume. You have to do this for every volume :(
|
I have code like
```
#define ONE 1
#define TWO 2
#define SUM (ONE+TWO)
```
How do I dump SUM as "3", the resolved value, in gcc 4.3+?
gcc -dM -E foo.honly seems to dump it as is. How do I get the actual value like it's inserted on compilation stage?
|
You can't. As far as the compiler is concerned, the lineprintf("%d\n", SUM)before preprocessing is indistinguishable from the lineprintf("%d\n", 1+2). The compiler just happens to perform an optimization calledconstant folding, even at the default optimization level (-O0), which turns the result into a constant 3 at... |
I came across=+as opposed to the standard+=today in some C code; I'm not quite sure what's going on here. I also couldn't find it in the documentation.
|
Inancientversions of C,=+was equivalent to+=. Remnants of it have been found alongside the earliest dinosaur bones.
For example, B introduced generalized assignment operators, usingx+=yto addytox. The notation came from Algol 68 via McIlroy, who incorporated it in his version of TMG. (In B and early C, the operator w... |
I have a macro defined. But I need to change this value at run time depending on a condition.
How can I implement this?
|
Macros are replaced by the preprocessor by their value before your source file even compiles. There is no way you'd be able to change the value of the macro at runtime.
If you could explain a little more about the goal you are trying to accomplish undoubtedly there is another way of solving your problem that doesn't ... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:In Java, what is the best way to determine the size of an object?
What is the technique to retrieve the # of bytes occupied by a class object/variable in Java?
Looking for an equivalent for SizeOf() operator in C.
|
I've used the SizeOf() project on Sourceforge before with decent success:
http://sourceforge.net/projects/sizeof/
However, based on how the JVM works, Sizeof for java is, at best, an intelligent guess based on predefined parameters rather than actually measuring the size of the memory allocation.
...so use this as ... |
I'm currently reading about enums in C. I understand how they work, but can't figure out situations where they could be useful.
Can you give me some simple examples where the usage of enums is appropriate?
|
They're often used to group related values together:
```
enum errorcode {
EC_OK = 0,
EC_NOMEMORY,
EC_DISKSPACE,
EC_CONNECTIONBROKE,
EC_KEYBOARD,
EC_PBCK
};
```
|
I am trying to find an implementation of a queue to use it to hold processes that are of type GDB. I have been looking all over the place and whatever I use I get an incompatible type when i try to enqueue the process of type GDB in the queue. Anyone knows an implementation of a queue that I can use or Hash_table ?
|
Any general-purpose queue worth using (including one you could roll on your own) should allow you to storevoid *, no questions asked.
So you should only store the address of whatever "process of type GDB" means.
|
I can't figure out how to set default value for integer in structure. For example
```
typedef struct {
char breed[40];
char coatColor[40];
int maxAge = 20;
} Cat;
```
The code above gives me an error on execution - Expected ';' at end of declaration list
|
You cannot specify default values in C. What you probably want is an 'init' style function which users of your struct should call first:
```
struct Cat c;
Cat_init(&c);
// etc.
```
|
C does not support function overloading. How can we then have 3 prototypes for main?
What is the historical reason for having 3 prototypes?
|
There are only two prototypes formainthat a standard-conforming C implementation is required to recognize:int main(void)andint main(int, char *[]). This is not overloading, since there can still only be onemainper program; having avoid foo(int, double)in one program and achar *foo(FILE *)in another isn't overloading e... |
I need help developing a circle detection algorithm to detect snooker balls. Does anyone know any algorithms that can be implemented in C and open cv? I'm having trouble getting this done
|
OpenCV 2.3 comes withHoughCircles. The C++ API for OpenCV 2.1 also implements the function:http://opencv.willowgarage.com/documentation/cpp/imgproc_feature_detection.html#HoughCircles
|
I'm trying to pass structure as pointer in function arguments. Here is my code
```
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
typedef struct {
int yearOfManufacture;
char model[50];
bool gasoline;
} Car;
void PrintCarDetails(Car details);
int main (int argc, const char * argv[])
{ ... |
Forward declaration should be :
```
void PrintCarDetails(Car * details);
```
|
I can get the list of running process from thethissource code on mac.
Now, I want to filter these processes for different users or at least for current user session.
|
You can just extend your code like this..
```
kinfo_proc *mylist;
size_t mycount = 0;
mylist = (kinfo_proc *)malloc(sizeof(kinfo_proc));
GetBSDProcessList(&mylist, &mycount);
char *user = getenv("USER");
for (int i = 0; i < mycount; i++)
{
uid_t uid = mylist[i].kp_eproc.e_pc... |
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question
I am including sys/socket.h, I still get compile time errors telling me that AF_INET is not defined. but st... |
check out thez/OS UNIX System Services socketssection in thez/OSXLC/C++Programming Guide. Make sure you're including the necessary header files and using the appropriate #defines.
|
How do you check whether a path is absolute or relative, using C on Linux?
|
Absolute paths tend to start with the/character. Anything else is pretty much relative from the working directory.
Even directories with..sequences in them are considered absolute if they start with/since they end up at the same position in the file system (unless you change links and things but that's beyond the dis... |
I have used fork() to create 2 different processes operating on 2 different address spaces.
Now, in parent process I need the value of a variable from child's address space or if the child process can modify the variable in parent's address space.
Is this possible?
|
No, once you've forked, each process gets itsownaddress space and you'll have to look into either:
some form of IPC between the processes to access each others data (such as shared memory or message queues).some more lighweight variant of fork that allows sharing of data (including possibly threading).
|
I want to assign 0 to all declared values in a single statement.
```
char r, g, b = 0;
```
The above only assigns 0 to b but not to the other variables
|
You can do it two ways:
```
char r = 0, g = 0, b = 0;
```
or
```
char r, g, b;
r = g = b = 0;
```
|
Hello i know a bit about pointers in C but the problem I am running into is how to access variables in an this typedef enum.
The structure is defined as:
```
typedef enum {
ZERO = (uint8_t) 0, ONE = (uint8_t) 1
} BIT;
typedef BIT lc3_word_t[16];
```
and the method that is calling it is:
```
word_not(lc3_word_t *R... |
You want to use (*A)[i], not *A[i].
|
I am a C beginner and needed a quick clarification regarding ints.
When you cast something as an int, which is 32 bits, half of the bits are allocated for negative integers. Thus, if you know that you will always have positive integers, casting something as an unsigned int should maximize your positive bits and thus... |
half of the bits are allocated for negative integersThis statement is not true, one bit is allocated to the sign for regular ints.
However, you are correct in your assumption. If you are positive the number is positive, usingunsigned intwill allow you to access number in the range [0,2^32), while the regular int will... |
I have 3 different processes that all print out single characters usingprintf. But I can't see them in the terminal. When I add a newline,printf("\n H")so each character is on a new line, I can see them. Why doesn't it work without the newline character?
|
Its a matter of flushing. If you flush the buffers after eachprintf, you should get output closer to what you want. To flush the standard output simply dofflush( stdout ).
|
What is the difference between the following initialization of a pointer?
```
char array_thing[10];
char *char_pointer;
```
what is the difference of the following initialization?
```
1.) char_pointer = array_thing;
2.) char_pointer = &array_thing
```
Is the second initialization even valid?
|
The second initialization is not valid. You need to use:
```
char_pointer = array_thing;
```
or
```
char_pointer = &array_thing[0];
```
&array_thingis a pointer to an array (in this case, typechar (*)[10], and you're looking for a pointer to the first element of the array.
|
I have an IP like this: 12.12.12.12I'm looping through different IP ranges (in 12.12.12.0/24 (example)) format, and trying to see if the IP is in the range.I have tried various methods such as inet_addr and comparing but I can't seem to get it.Is there an easy way to do this? I'm using Windows.
|
Just test whether:
```
(ip & netmask) == (range & netmask)
```
You can determine the netmask from the CIDR parametersrange/netbitsas follows:
```
uint32_t netmask = ~(~uint32_t(0) >> netbits);
```
|
Here is my code.
```
#include<stdio.h>
int main(int argc,char** argv)
{
FILE* fp;
fp=fopen(argv[1],"r");
struct element{
int value;
char activity;
};
typedef struct element element;
element a;
printf("%d",feof(fp));
}
```
Now if I don't give the lastprintfcommand it doe... |
Check the return value offopen(well, check the return value ofanycall), it probably failed to open the file.
|
I wrote this function in C, which is meant to iterate through a string to the next non-white-space character:
```
char * iterate_through_whitespace(unsigned char * i){
while(*i && *(i++) <= 32);
return i-1;
}
```
It seems to work quite well, but I'm wondering if it is safe to assume that the*iwill be evaluat... |
The standard says:
A byte with all bits set to 0, called the null character, shall exist
in the basic execution character set; it is used to terminate a
character string.
|
I'm trying to generate a date string from current time to put into HTTP response header. It looks like this:
```
Date: Tue, 15 Nov 2010 08:12:31 GMT
```
I only have the default C library to work with. How do I do this?
|
Usestrftime(), declared in<time.h>.
```
#include <stdio.h>
#include <time.h>
int main(void) {
char buf[1000];
time_t now = time(0);
struct tm tm = *gmtime(&now);
strftime(buf, sizeof buf, "%a, %d %b %Y %H:%M:%S %Z", &tm);
printf("Time is: [%s]\n", buf);
return 0;
}
```
See thecode "running" at codepad.
|
Does anyone has an idea for efficient error correction algorithm?
Suppose all the operations and manipulation on the stream is on
the Byte level.
|
MaybeReed-Solomon error correction?
|
I'm new to Motif programming and I want to use UTF-8 encoding.
I've triedXtSetLanguageProc (NULL, NULL, NULL);but when I read a file in Motif (editor text-like in 6A volume motif programming), I've got problems with accented characters.
I had to usesetlocale()?
thanks!
|
With Motif, you have to switch to the correct font for the languages that you are using. There is currently no single UTF-8 font that has full support for all languages.
If there is more to your problem you might want to ask it on MotifZonehttp://www.motifzone.com/forum/unicode-supportsince Motif is not a commonly us... |
I am developing in Cocoa / Xcode and have anint *array containing values.
When I want to usememcpyto shift values in the array, it transfers only 0s.
e.g.
Array contains values as 1 2 3 4memcpy(array,array+2*sizeof(int),2*sizeof(int));
result: 0,0,3,4
Is there a better alternative to memcpy, or something I am doin... |
I think the right way to do what you want is:
```
memcpy(array, array + 2, 2*sizeof(int));
```
That's because in the 2nd argument of memcpy pointer arithmetic is being done, and anything that's being added to "array" pointer is considered as being a multiple of an integer's size. So in this case saying "array + 2" m... |
In a facebook group, I saw a question like :
If a row dominated two dimensional array in the following which one is advantage and why?
```
a) for(i=0;i<1000;i++)
for(j=0;j<1000;j++)
temp=temp+a[i][j];
b) for(j=0;j<1000;j++)
for(i=0;i<1000;i++)
temp=temp+a[i][j]
```
From my point I c... |
There is no difference in theory.
The practical advantage is in cache locality. If you access locations which are far apart, you increase the number of cache misses, which in turn makes the code run slower.
Depending on your processor cache size, you would perhaps need to replace 1000 with some reasonably bigger num... |
I have a following code(which is taken from a C book):
```
#include<stdio.h>
int main( )
{
int k=4,j=0;
switch(k)
{
case 3:
j=300;
case 4:
j=400;
case 5:
j=500;
}
printf("%d",j);
}
```
When i run the above code, I get output as500, but I expected it to be400, can anyone why it is bee... |
You need tobreak;at the end of a case block.
```
#include <stdio.h>
int main()
{
int k = 4, j = 0;
switch(k)
{
case 3:
j = 300;
break;
case 4:
j = 400;
break;
case 5:
j=500;
break;
}
printf("%d\n", j);
... |
Is it possible to check whether a Windows installation is Genuine or not programmatically?
Lets just say I want to check Windows 7 from C, C++, Java or Python.
|
this from CodeProject, in C++ (Check for Windows Genuine in VC++)
```
#include <slpublic.h>
#pragma comment(lib,"Slwga.lib")
bool IsWindowsGenuine()
{
GUID uid;
RPC_WSTR rpc=(RPC_WSTR)_T("55c92734-d682-4d71-983e-d6ec3f16059f");
UuidFromString(rpc,&uid);
SL_GENUINE_STATE state;
SLIsGenuineLocal(&u... |
Are there any difference that I should choose one over the other?
|
They achieve the same result but belong to different APIs, so they return their results and report errors in different ways.
If you're already using other routines from either API, pick that one. If not, SetCurrentDirectory() is more "Windowsy", while _chdir() is more similar to the POSIX API. If you have a mind to p... |
I'd like to implent a function forSuperFastHashthat is compatible so openssl's MD5 function.
MD5 is declared in md5.h as:
```
unsigned char *MD5(const unsigned char *d, size_t n, unsigned char *md);
```
But I can't find it's definition in the headers and the sourcecode.
So how does it work exactly? The function not... | ERROR: type should be string, got "\nhttps://www.rfc-editor.org/rfc/rfc1321\n" |
I triedutime()on both Windows (XP) and Linux. On Windows I get anEACCESerror, on Linux I don't get any error (but the time is not changed). Myutime()code is fine, because it works on files. I could not find ifutime()is supposed to work on directories or not, but if not, how can I change the time and date?
I am lookin... |
For Windows you can use theSetFileTimewhich also works for directories.
|
I have a number of.cand.hfiles with some parts of the code disabled by putting the code block in pre-processor directives e.g.
```
#ifdef FOOBAR
// some code that can be compiled if needed by defining FOOBAR in pre-processor.
#endif
```
No I need to defineFOOBARsuch that its defined for every file that is compiled b... |
Add the compiler option-DFOOBARto the make variableCFLAGS
|
When I compile this little program instead of displaying "num1:7,num2: 2",
it displays "num1:-1218690218,num2:-1217453276". I think I'm not specifying what the program should display so its just giving me the int range instead.
I'm sorry.
```
#include <stdio.h>
main() {
int num1 = 7, num2 = 2;
... |
You've put the closing parenthesisbeforenum1andnum2, so they're not being passed toprintf. You need to change this:
```
printf("num1:%d , num2:%d\n"), num1, num2;
```
to this:
```
printf("num1:%d , num2:%d\n", num1, num2);
```
Yes, the parenthesis is the only change, but it's crucial.
|
I want tosend(socketfd, ...)and I'm using theselect()function. Should this file descriptor be in thewritefds, or in thereadfds?
|
readfdsare for sockets you want to read from,writefdsfor those you want to write to. Sowritefdsin your case.
|
I am using C and writing a client-server program, and I would like to get an unused port number to run my server process. My server code is like this:
```
getaddrinfo()
socket()
bind()
listen
while(1)
accept()
```
I need to provide the unused port addr to the bind() call. But I do not want to pass the port number ... |
Just bind() your socket setting sin_port to 0 in sockaddr_in. System will automatically select unused port. You can retrieve it by calling getsockname().
But I don't have any idea how to pass it to client, except printing it and using as command-line parameter for client program.
|
I have a following array and a printf() stament,
```
char array[1024] = "My Message: 0x7ffff6be9600";
printf("%.14s", strstr(array, " 0x") + 1);
```
The output of above printf() is 0x7ffff6be9600,
can we store it into a unsigned long variable?
|
Look atsscanf
|
I'm using PC Lint for the first time. I was "linting" my code, when PC Lint warns me about mywhile(TRUE).
This is what it says:
716: while(1) ... -- A construct of the form while(1) ... was found.Whereas this represents a constant in a context expecting a Boolean,
it may reflect a programming policy whereby infin... |
The text says that althoughwhile(TRUE)(which gets preprocessed intowhile(1)) is a perfectly valid infinite loop, the more conventional form of writing an infinite loop is
```
for(;;)
{
...
}
```
because it doesn't use any values at all and therefore is less error-prone.
|
I've split some code into two files, it was working before. In one file I have a function which has an out value parameter which is a pointer to a pointer.
I'm filling this parameter with a call to a getter and dereferencing it:
```
foo(&bar());
```
however I get an error saying ''&' requires an l-value'. I underst... |
Well, you need an lvalue, i.e. something that can be assigned to. You can't assign to the return value of a function.
You need to do something like this:
```
temp = bar();
foo(&temp);
```
|
MSDN says that afterCryptVerifySignature()you cannot reuseHCRYPTHASHobject to try hashing more data, instead it says you need to recreate it withCryptDestroyHash()andCryptCreateHash().Reusing really fails.
Anyone is familiar with a hack that can save these calls, or it is really impossible?
|
I imagine theHCRYPTHASHdata structure is more flexible than just being used to call withCryptVerifySignature(). It's designed to operate on a (possibly discontinuous) stream of data (viaCryptHashData()), which means it stores some state within it on the hash's current values. Therefore, once you've used it on a stre... |
I want to keep some applications to run with a 4 GB address space within a 64 bit OS running on a 64 bit processor (x86 xeon, 8 core). I know there is an option to compile with -m32 option, but at this moment the computer I'm working with, doesn't have the required support for compiling with -m32, so I can't use it, n... |
The ulimit/setrlimit mechanism, accessible in bash via ulimit, can do this with minor drawbacks.
```
ulimit -v 4000000
```
should limit the memory available to the current process group to 4 GB.
However, it limits the totalsizeof your address space mappings, and does not limit your mappings' offset
- you still may ... |
see i have written one program for big endian now i dont have big endian machine but i want to check whether my program will works correctly or not on big endian so how can i check that on my little endian pc.?
Is there any online virtual big-endian compiler ?
note : i have googled about this but did not get anythin... |
qemucan virtualize all sorts of architectures, amongst then big endian ones.
|
Is there a LPTSTR equivalent of _strnicmp which takes in 2 LPTSTR strings, and number of TCHARs to compare until?
using the c winapi btw
|
It is_tcsncicmp, seethe documentation.
|
The same code ran in TURBO C.
```
struct details
{
char name[20];
int year;
float price;
}my_str;
details book1[10];
```
This error is produced. How can this be fixed?
```
ram.c: In function ‘main’:
ram.c:11:1: error: ‘details’ undeclared (first use in this function)
ram.c:11:1: note:... |
There are two ways to fix this:
Change second line to this:
```
struct details book1[10];
```
Or you can change the declaration to:
```
typedef struct{
char name[20];
int year;
float price;
} details;
```
C is slightly different from C++, so you can't declare structs quite the same way.
|
suppose I have a string "2011-08-21 21:48:45 +1200",and another one with the same format,I want to compare these 2 strings to find out which one is the early one or later one,is there a easy way to convert a string to time format rather than compare them by characters?
Thanks
|
usegetdateorstrptime().
|
Here's the statement:
```
int i;
scanf("%d ",&i);
```
Why does the space at the end of the format string causes scanf to accept two inputs instead of 1?
|
The space at the end of the format string tells scanf to eat whitespace after the first integer. It's not actually accepting a second input. When you do enter a second value, scanf sees that the whitespace is finished it returns, storing the first integer into your variable i. The "second input" is still in the sta... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.