question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I don't want to use system() in my C program, because system(3) blocks and this is not what I want. What is the optimal way to do it?
|
I think that a quick and dirty action is to call sytem(command &). the & will spawn the new process.
|
What is the fastest way to count lines and words in a text file in pure ANSI C?
A word is terminated by a space or period. Line is terminated by'\n'.
This seems to be in C++.
|
Read the file inIterate over charactersincrement character counterCheck if space/end of lineincrement word counterRepeat second and third steps untilEOF
|
I'm currently trying to test astrcat()function that I wrote myself. Instead of printing the outputs and checking them line by line manually, I've decided to use assert from assert.h. The problem is that assert is showing errors even though the outputs look totally fine. The following is my code:
```
void mystrcat_test()
{
char str[BUFSIZ];
assert(strcmp(str, ""));
mystrcat(str, "hello");
assert(strcmo(str, "hello"));
}
```
|
strcmpreturns 0 if both strings are same.asserttakes 0 (false) as an indication that the test failed and will report error. So the test should be:
```
assert(strcmp(str, "") == 0);
```
|
Given a .so file and function name, is there any simple way to find the function's signature through bash?
Return example:
```
@_ZN9CCSPlayer10SwitchTeamEi
```
Thank you.
|
My compiler mangles things a little different to yours (OSX g++) but changing your leading @ to an underscore and passing the result to c++filt gives me the result that I think you want:
```
bash> echo __ZN9CCSPlayer10SwitchTeamEi | c++filt
CCSPlayer::SwitchTeam(int)
```
doing the reverse is trickier as CCSPlayer could be a namespace or a class (and I suspect they're mangled differently). However since you have the .so you can do this:
```
bash> nm library.so | c++filt | grep CCSPlayer::SwitchTeam
000ca120 S CCSPlayer::SwitchTeam
bash> nm library.so | grep 000ca120
000ca120 S __ZN9CCSPlayer10SwitchTeamEi
```
Though you might need to be a bit careful about getting some extra results. ( There are some funny symbols in those .so files sometimes)
|
I know when I have to print I usep->realand so on but what should I write when I am reading numbers usingscanf?
```
#include <stdio.h>
typedef struct {
int real;
int imaginary;
} complex;
void read(complex*);
void main() {
complex c;
read(&c);
}
void read(complex* p){
/*what to write in scanf*/
}
```
|
You can write:
```
scanf("%d %d", &p->real, &p->imaginary);
```
but that depends heavily on the format in which the numbers come.
|
Can we pass variable number of arguments to a function in c?
|
Hereis an example:
```
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
int maxof(int, ...) ;
void f(void);
int main(void){
f();
exit(EXIT SUCCESS);
}
int maxof(int n_args, ...){
register int i;
int max, a;
va_list ap;
va_start(ap, n_args);
max = va_arg(ap, int);
for(i = 2; i <= n_args; i++) {
if((a = va_arg(ap, int)) > max)
max = a;
}
va_end(ap);
return max;
}
void f(void) {
int i = 5;
int j[256];
j[42] = 24;
printf("%d\n", maxof(3, i, j[42], 0));
}
```
|
I have been trying to use fflush to make a progress bar.
To test fflush, I wrote the small code below.
It works as it supposed to when I uncomment "sleep(1);"
but it works in an unexpected way if
it remains commented out. It prints the first dash, waits than prints all remaining
9 of them and quits.
I don't understand why it makes a difference.
```
int main()
{
int f,j;
j =0;
for(f=0;f<10;f++)
{
printf("-");
fflush(stdout);
while(j++<1000000000);
//sleep(1);
}
}
```
|
You need to setjback to zero after the while loop. The next iteration it will just skip over the while loop.
|
I'm new to C and still trying to grasp the concept of pointers. I know how to write a swap function that works...I'm more concerned as to why this particular one doesn't.
```
void swap(int* a, int* b)
{
int* temp = a;
a = b;
b = temp;
}
int main()
{
int x = 5, y = 10;
int *a = &x, *b = &y;
swap(a, b);
printf(“%d %d\n”), *a, *b);
}
```
|
You're missing*s in the swap function. Try:
```
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
```
That way, instead of just swapping the pointers, you're swapping theints that the pointers are pointingto.
|
If I open a file and use fscanf to read a file like this:
2 411 501 46....
How do I tell C to read the first number and store it as a variable, then the second as another variable, run a loop, then move on to the next set?
|
A loop like this is what you're after:
```
int type, stories;
while (fscanf(buildingFile, "%d %d", &type, &stories) == 2)
{
printf("Got type=%d, stories=%d\n", type, stories);
/* Do something with 'type' and 'stories' */
}
if (ferror(buildingFile))
{
perror("buildingFile");
}
```
|
I need to open a cash drawer using C/C++ or Java. It is a POS-X cash box with a USB connection. I've never done anything like this before. I noticed the cash box was linked to the "COM3" port. I know Java does not have a USB API so I turned to C/C++.
|
Forum post about ithere.
In a nutshell, install the driver, change the COM3 baud rate to 9600, and send a "1" to the COM port.
Check outjavax.commfor a method of communicating with a com port on java.
|
Lookign at:http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/
for string (%.Ns) precision.
When I use sizeof or a #define length in the precsion it reads it as actual text.
Why is this? What are the rules of this? Does it have to be an integer value only?
i.e. -
```
buffer[50];
sprintf (buffer, "%.sizeof(buffer)s", string);
```
or
```
#define MAX_LEN
sprintf (buffer, "%.MAX_LENs", string);
```
Thanks
|
Anything inside quotation marks is part of the string, and the compiler won't even think of touching it. Instead, you can use a '*' to letsprintfknow your precision is an extra argument it can read. Also, you need the '.' before your precision, or otherwise it will be a pad-width instead.
```
sprintf(buffer, "%.*s", (int) sizeof(buffer), string);
```
|
Can I call another function in a thread runner function, called by apthread_create()? Are there any restrictions on such functions?
|
Yes, you can (and doing so is fairly frequent). The main restriction is that you need to synchronize threads when two or more access the same data (at least if there's any chance that any of them might modify that data).
|
How do I write this C expression inJ? (wherexis input integer, andais temporary variable)
```
((a= ~x & (~x >> 1)) ^= a ? 0 : (a ^ (a & (a - 1))) | (a ^ (a & (a - 1))) << 1);
```
.
Edit:
In a more readable form:
```
int a = (~x) & ((~x) >> 1);
if (a == 0) return 0;
int b = a ^ (a & (a - 1));
return b | (b << 1);
```
|
Without testing, the basic transcription would be something like this:
```
Shift =: (33 b.)
And =: (17 b.)
Not =: (26 b.)
Xor =: (22 b.)
Or =: (23 b.)
BastardFunction =: 3 : 0
a =. (Not y) And (_1 Shift (Not y))
if. a do.
b =. a Xor (a And a - 1)
(1 Shift b) Or b
else.
0
end.
)
```
But there could be a smarter approach.
|
Is there a method to return the identifier string for a given element's numerical value? For instance, logging a UITouch's phase returns an int, but having the actual string value would be easier to read.
I suppose I could write my own switch statement to do this, but I'm hoping there's a built-in means.
|
No. But if you're looking for a relatively-neat way of maintaining your own solution to this (e.g. a switch statement), you could investigate X-macros (see e.g.http://www.drdobbs.com/184401387).
|
I'm wondering what sort of algorithm could be used to take something like "4.72" into a float data type, equal to
```
float x = 4.72;
```
|
scanf,operator>>for istreams, andstrtofwould be the obvious choices.
Thereisalsoatof, but, likeatoi, it lacks a way to tell you there was an error in the input, so it's generally best to avoid both.
|
Suppose I want to read an entire file in memory. I'd open it in binary mode, usefseekto get to the end of the file, then doftellto get its size.
Then I would allocate a string with the same size as the file, and just read it in, right?
The problem is thatftellreturns along int, andmallocshould receive asize_targument. Now,size_tcanbe larger thanlong intas far as I can tell (I've just checkedC: a reference manualby Harbison and Steele, and Chapter 11 mentions thatsize_tcan be defined asunsigned long long, depending on the compiler). I suppose the opposite could be true (and that would be a real problem, since I'd be casting along longinto along, or something like that)
So my question is how do I deal with that?
Thanks!
edit:thanks guys, that was really quick! I'll usemmap(andposix_madvisetoo, which I've found after diggin up info aboutmmap)!
|
I think you want to use mmap() instead.
|
Actually I've (probably) a "simple" problem. So I don't know how to cast a signed integer to an unsigned integer.
My code :
```
signed int entry = 0;
printf("Decimal Number : ");
scanf("%d", &entry);
unsigned int uEntry= (unsigned int) entry;
printf("Unsigned : %d\n", uEntry);
```
If I send the unsigned value to the console (see my last code line), I always get back an signed integer.
Can you help me?
Thanks a lot!
Kind regards, pro
|
```
printf("Unsigned : %u\n", uEntry);
// ^^
```
You must use the%uspecifier to tell theprintfruntime that theuEntryis anunsigned int. If you use%dtheprintffunction will expect anint, thus reinterpret your input back to a signed value.
|
Is it possible to change the number of bytes a long has in visual studio?
Currently when compiling C code sizeof(int) and sizeof(long) are both equal to 4.
|
Since you're using Visual Studio, presumably your target platform (and the libraries you're using) target Windows. The Win64 platform uses an LLP64 model (http://msdn.microsoft.com/en-us/library/aa384083.aspx) whereintandlongare 32-bits. It would be futile I think to try to makelonga 64-bit type in that situation.
Useint64_t(fromstdint.h) orlong longor similar to get a 64-bit integer type
|
In C, is it possible to define a union within another union? If no, why is it not possible? Or if yes, where can it be used?
|
Suppose you want to define:
```
union myun {
int x;
sometype y;
};
```
wheresometypeis atypedefdefined by a library you're using. If the library happened to implement it as a union type, then this would be a union within a union, and it would make sense because you can't (from a good design standpoint) violate the encapsulation of the library's type.
|
I want to make some printf's to the windows console from my C program but want to make some of them different colours.
Anyone know if this can be done easily?
EDIT: Windows XP is my OS
|
SetConsoleTextAttribute()will let you set the color of subsequent text output.
http://msdn.microsoft.com/en-us/library/ms686047.aspx
You'll probably want to look at the complete set of Win32 console APIs to be able to get/set/restore and otherwise manipulate the console.
http://msdn.microsoft.com/en-us/library/ms682073.aspx
|
From my lecture slides, it states:
As illustrated in the code below an array name can be assignedto an appropriate pointer without the need for a preceding & operator.
```
int x;
int a[3] = {0,1,2};
int *pa = a;
x = *pa;
x = *(pa + 1);
x = *(pa + 2);
a += 2; /* invalid */
```
Why isa += 2;invalid?
Can anyone help clarify?Also feel free to edit the title if you think of a better one.
|
a += 2gets translated toa = a + 2. Adding a number to an array is the same as adding a number to a pointer which is valid and yields a new pointer.
The assignment is the problem - arrays are not lvalues, so you cannot assign anything to them. It is just not allowed. And even if you could there is a type mismatch here - you’re trying to assign a pointer to an array which does not make sense.
|
On my system, I get:
```
sizeof ( int ) = 4
sizeof ( long ) = 4
```
When I checked with a C program, bothint&longoverflowed to the negative after:
```
a = 2147483647;
a++;
```
If both can represent the same range of numbers, why would I ever use thelongkeyword?
|
inthas a minimum range of -32767 to 32767, whereaslonghas a minimum range of -2147483647 to 2147483647.
If you are writing portable code that may have to compile on different C implementations, then you should uselongif you need that range. If you're only writing non-portable code for one specific implementation, then you're right - it doesn't matter.
|
I've wrote CGI script for www.
This script expects two parameters through GET method, multiply these numbers and write result into the file.
```
mult.cgi?m=1&n=2
```
But now I want to use this script from console too.
I'tried something like
```
./mult.cgi?m=1&n=2
```
But it didnt work, how can I send parameters to script?
thanks.
|
```
QUERY_STRING="m=2&n=4" ./mult.cgi
```
|
Can anyone give me an example of a Java program which has two native methods declared and defined in C and C++. Actually, I need a procedure as well as the code, so that I can run it and learn from it, thanks.
|
You can do it with JNI [Java Native Interface]
Check this tutorial WIN env
LinuxEnvironment :-) better one
|
The ISO C standard allows three encoding methods for signed integers: two's complement, one's complement and sign/magnitude.
What's an efficient or good way to detect the encoding at runtime (or some other time if there's a better solution)? I want to know this so I can optimise a bignum library for the different possibilities.
I plan on calculating this and storing it in a variable each time the program runs so it doesn't have to be blindingly fast - I'm assuming the encoding won't change during the program run :-)
|
You just have to check the low order bits of the constant-1with something like-1 & 3. This evaluates to
for sign and magnitude,for one's complement andfor two's complement.
This should even be possible to do in a preprocessor expression inside#if #elseconstructs.
|
Is it possible to change the number of bytes a long has in visual studio?
Currently when compiling C code sizeof(int) and sizeof(long) are both equal to 4.
|
Since you're using Visual Studio, presumably your target platform (and the libraries you're using) target Windows. The Win64 platform uses an LLP64 model (http://msdn.microsoft.com/en-us/library/aa384083.aspx) whereintandlongare 32-bits. It would be futile I think to try to makelonga 64-bit type in that situation.
Useint64_t(fromstdint.h) orlong longor similar to get a 64-bit integer type
|
In C, is it possible to define a union within another union? If no, why is it not possible? Or if yes, where can it be used?
|
Suppose you want to define:
```
union myun {
int x;
sometype y;
};
```
wheresometypeis atypedefdefined by a library you're using. If the library happened to implement it as a union type, then this would be a union within a union, and it would make sense because you can't (from a good design standpoint) violate the encapsulation of the library's type.
|
I want to make some printf's to the windows console from my C program but want to make some of them different colours.
Anyone know if this can be done easily?
EDIT: Windows XP is my OS
|
SetConsoleTextAttribute()will let you set the color of subsequent text output.
http://msdn.microsoft.com/en-us/library/ms686047.aspx
You'll probably want to look at the complete set of Win32 console APIs to be able to get/set/restore and otherwise manipulate the console.
http://msdn.microsoft.com/en-us/library/ms682073.aspx
|
From my lecture slides, it states:
As illustrated in the code below an array name can be assignedto an appropriate pointer without the need for a preceding & operator.
```
int x;
int a[3] = {0,1,2};
int *pa = a;
x = *pa;
x = *(pa + 1);
x = *(pa + 2);
a += 2; /* invalid */
```
Why isa += 2;invalid?
Can anyone help clarify?Also feel free to edit the title if you think of a better one.
|
a += 2gets translated toa = a + 2. Adding a number to an array is the same as adding a number to a pointer which is valid and yields a new pointer.
The assignment is the problem - arrays are not lvalues, so you cannot assign anything to them. It is just not allowed. And even if you could there is a type mismatch here - you’re trying to assign a pointer to an array which does not make sense.
|
On my system, I get:
```
sizeof ( int ) = 4
sizeof ( long ) = 4
```
When I checked with a C program, bothint&longoverflowed to the negative after:
```
a = 2147483647;
a++;
```
If both can represent the same range of numbers, why would I ever use thelongkeyword?
|
inthas a minimum range of -32767 to 32767, whereaslonghas a minimum range of -2147483647 to 2147483647.
If you are writing portable code that may have to compile on different C implementations, then you should uselongif you need that range. If you're only writing non-portable code for one specific implementation, then you're right - it doesn't matter.
|
I've wrote CGI script for www.
This script expects two parameters through GET method, multiply these numbers and write result into the file.
```
mult.cgi?m=1&n=2
```
But now I want to use this script from console too.
I'tried something like
```
./mult.cgi?m=1&n=2
```
But it didnt work, how can I send parameters to script?
thanks.
|
```
QUERY_STRING="m=2&n=4" ./mult.cgi
```
|
Can anyone give me an example of a Java program which has two native methods declared and defined in C and C++. Actually, I need a procedure as well as the code, so that I can run it and learn from it, thanks.
|
You can do it with JNI [Java Native Interface]
Check this tutorial WIN env
LinuxEnvironment :-) better one
|
The ISO C standard allows three encoding methods for signed integers: two's complement, one's complement and sign/magnitude.
What's an efficient or good way to detect the encoding at runtime (or some other time if there's a better solution)? I want to know this so I can optimise a bignum library for the different possibilities.
I plan on calculating this and storing it in a variable each time the program runs so it doesn't have to be blindingly fast - I'm assuming the encoding won't change during the program run :-)
|
You just have to check the low order bits of the constant-1with something like-1 & 3. This evaluates to
for sign and magnitude,for one's complement andfor two's complement.
This should even be possible to do in a preprocessor expression inside#if #elseconstructs.
|
For example if I write to a particular memory location (ex: DMA transfer) how does it get affected in my cache?
|
The cache is a CPU feature; if you write to memory via the CPU, the cache will be updated and will remain consistent.
If you write to memory some other way (e.g. a DMA transfer, as you suggest) you will need to (possibly) flush the cache beforehand, and then tell the CPU that the cache is invalid. How you do this depends on your system - for example seeINVDandWBINVDfor x86.
Two good articles to read on cache coherency and DMA areUnderstanding CachingandUsing DMA(both by James Bottomley, published in Linux Journal; "Caching" in issue 117, January 2004 and "DMA" in issue 121, May 2004).
|
I want to forward packets by netfilter, so I want to get some c demos to get start, thanks
|
Did you look at thenetfiltersite? The documentation seems a bit dated, but there's a "Linux netfilter Hacking HOWTO" there.
Then play with thesource:)
|
I'm making a game that will allow content development and I'd like it to be sort of a DLL based system. But, my game works for Linux (X86 arch) , Mac OSX and 32 bit Windows. Is there a way I could allow content developers to compile only one thing and have it work based on the platform? I fear it might get confusing if there are 3 versions per plugin. What could I do?
Thanks
|
You can decide to use a cross-platform scripting environment like Lua for plugins. This is essentially what most cross-platform games do.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 years ago.Improve this question
Can you please explain to me what is happening here?
```
char data[128]; // Create char array of size 128.
long * ptr; // Create a pointer.
ptr = (long *) data; // ??
```
Mainly, what does the (long *) mean?
Does it mean that the data is of type char, and I am casting the reference to data as a reference to a long?
Thank you.
|
The(long*)expression is a C style cast. It treates the memory pointed to bydataand treats it as a pointer to data of typelong
|
The following code (a function prototype):
```
void parse_ini(FSFILE *fp, void(*secFunc)(char*), void(*varFunc)(char*, char*));
```
presents errors when compiled:
```
util\setup.c:38: error: syntax error before '*' token
util\setup.c:38: error: 'parse_ini' declared as function returning a function
util\setup.c:38: error: syntax error before 'void'
util\setup.c:50: error: syntax error before '*' token
```
What is causing this? Using MPLAB C30, which is a version of GCC v3.23 for PIC24F/dsPIC 16-bit microcontrollers.
|
I'd guess that you haven't included a header that declares/definesFSFILE.
|
Looking at the code:
```
int i = 5;
if (i = 0)
{
printf ("Got here\n");
}
```
What does the C standard have to say about what will get printed?
Or in more general terms does the assignment happen first or the comparison?
|
§6.8.4 says that the syntax for anifselection statement is:
```
if( expression )statement
```
Further in this section, it mentions that if the expression compares unequal to 0, thenstatementis executed. The expression must therefore be evaluated before it can be compared to 0.i = 0is an expression which evaluates to 0. For further reference, see §6.5 “Expressions” with regards to §6.5.16 “Assignment operators”, in particular note this excerpt:
An assignment operator stores a value in the object designated by the left operand. An
assignment expression has the value of the left operand after the assignment, but is not an lvalue.
|
What do modern companies use to compile and link their projects?
Especially with large projects, makefiles don't seem usable enough to be scalable. As far as I can tell, many companies use either in-house build systems or in-house scripts on top of existing build systems.
Do large projects use make?
Is pure Ant, Maven, etc used or is it wrapped with some script?
|
A lot useCMakethese days, which auto-generates makefiles for various platforms. UnfortunatelyCMakehas its own (weird) internal language, which is why I personally preferSCons- anything it can't do naturally can be easily added - after all it's just Python code. Take a look at thelist of OS projects using SCons. Many of them are quite large and non-trivial multi-platform builds.
|
What packages do i need to install in order to use a Makefile. I've already installed cmake, would i need ocamlmakefile?
My problem is that whenever i type 'make' into the terminal, i'm told "make command not found".
|
You need GNU make.
CMake and other make programs use other filenames generally.
|
I have an issue regarding freeing memory as under:
```
string points; // some points sequences
char* charPoints = (char*)malloc((points.length() +1) * sizeof(char));
//do something
free(charPoints);
```
Even then after freeing memory is leaked when checked with instruments
|
The pointer you pass tofreemust be the same one which returned bymalloc. If you pass a different pointer it will result in a undefined behavior. Take a copy of the pointer before you do the operation such as incrementing thecharPointsand then pass this original pointer tofreefunction to properly release memory.
|
It just occurred to me That I don't know how to initialize a pointer to pointer from a non pointer value with one statement in C++:
```
int a = 1;
int** ppa = &&a; //Does not compile
int** ppa = &(&a); //Does not compile
int* pa = &a; //Works but is a
int** ppa = &pa; //Two step solution
```
Am I missing something, is the two statement the one and only way to do it?
|
if you want a pointer to a pointer, the pointer that you want to point to must be located somewhere in memory, so I think there cannot be a "one step solution" because you need a pointer variable that you can point to.
(Note: This sentence is not meant to be a linguistic trial to use "point" as often as possible in one sentence :-))
|
I understand that there's no String data type in C. What I want to do is get an input string from the user and store it to a variable without having to define how many characters it needs to have. Can I do that using linked lists? I want to avoid putting it to a character array as much as possible so linked lists are the only thing I can think of but I don't know how to.
|
Youcoulddo it in a linked list, but a linked list of char will generally be an extremely inefficient data structure -- each node will have one char and (at least) one pointer. In a typical case, you're looking at 4 or 8 bytes for the pointer and one for the char, so you're imposing alotof overhead.
My immediate recommendation would be to put at least 16 characters in each node in your linked list to keep the overhead at least sort of reasonable. Of course, a dynamic array will usually be better still, but at least that will keep a linked list from beingtotallyunreasonable.
|
I have a buffer of pixel values. Is it possible to display that buffer as an image using pixbuf in gtk. i will be using c language.
|
yes, have a look at the function:
```
gdk_pixbuf_new_from_data ()
GdkPixbuf * gdk_pixbuf_new_from_data (const guchar *data,
GdkColorspace colorspace,
gboolean has_alpha,
int bits_per_sample,
int width,
int height,
int rowstride,
GdkPixbufDestroyNotify destroy_fn,
gpointer destroy_fn_data);
```
(In thedocs)
|
Addresses of 1d arrays are actually taken as
```
a[i]=*(a+i);
```
Are the addresses of 2d arrays calculated as
```
a[i][j]=**(a+i+j);
```
|
The other answers are not quite correct. It's more like:
```
*(*(a+i)+j)
```
|
I have to output a large number, a double precision number using the following code:
```
fprintf(outFile," %11.0f %d O(g(n))",factorialNotRecursive(index,factCount),factValue);
```
now the number gets so big that it jumps out of alignment further down the
list of output. Once it gets past 11 digits, the max specified it continues
to grow larger. Is there a way to cope with this? I'm not sure how big the inputs
that will be run on this program.
|
I think you cannot do it directly. You have to print to a string, then change the string.
```
/* pseudo (untested) code */
value = factorialNotRecursive(index, factCount);
/* make sure buff is large enough (or use snprintf if available) */
n = sprintf(buff, "%11.0f", value);
if (n > 11) {
buff[10] = '+';
buff[11] = 0;
}
fprintf(outFile," %s %d O(g(n))", buff, factValue);
```
|
I have a problem here and need your help. I've been trying to capture keyboard strokes from a created window using cvWaitKey() function. The function works fine if I called the cvWaitKey from the same thread that created the window, but when I create the window from a thread and call cvWaitKey() from another thread it doesn't return correct key, it blocks for cvWaitKey(0) and returns -1 for any timeout grater than zero.
|
Yes, this cannot work. cvWaitKey() is implemented by calling the PeekMessage() API function. That can only see messages on the message queue which is associated with the thread. The thread you created doesn't have any windows.
There is no obvious workaround for this, you have to call it on the thread that created the window. Calling GetAsyncKeyState() could work, a very different approach though.
|
I've seen
```
for(;;)
```
and
```
for ( ; *s != '\0'; s++)
```
Why is it blank like that. Thanks.
|
Theforstatement works like:
for (initialization; test-condition; update)
And any or all of those three can be omitted (left blank). So:
for (;;)is an infinite loop1equivalent towhile (true)because there is no test condition. In fact,for (int i=0; ;i++)would also be an infinite loop1.for ( ; *s != '\0'; s++)is a loop with no initialization.swill point to the beginning of (probably) a string and is incremented until it reaches the null character'\0'denoting end-of-string. This essentially means loop through all characters of the strings
1The loop will still be interrupted if there's abreakstatement in the loop body, or a call toexit(), etc...
|
I need to compute a number (a/(2**b) using only bitwise operators such as ! & ^ ~ and shifts. I was given the following hint but I'm new to C and I dont know what the code means:
```
int bias = x>0 ? 0 : ((1<<n)-1);
```
Can anyone explain it to me?
I thought a>>b would work but I dont think it works for negative numbers.
|
That particular bit of code gives you a bias of 0 if x is positive. Otherwise it produces a mask of the lower n bits. Thex = a ? b : c;pattern is called theternary operator(technically the 'conditional operator', apparently) in C.
```
n (1<<n) (1<<n)-1 binary
0 0x01 0x00 00000000
1 0x02 0x01 00000001
2 0x04 0x03 00000011
3 0x08 0x07 00000111
4 0x10 0x0F 00001111
5 0x20 0x1F 00011111
6 0x40 0x3F 00111111
7 0x80 0x7F 01111111
...
```
|
This one is for all you ALSA guys. I need a sanity check here. I am using the the alsa-lib api to play sounds and the function that I am using to write the data to the driver is
```
snd_pcm_sframes_t snd_pcm_writei (snd_pcm_t* pcm,
const void* buffer,
snd_pcm_uframes_t size);
```
For the third parameter, should it be the frame count or the size of the buffer in bytes? I'm asking because I have seen numerous examples where the size in bytes is passed in. One example is included in thedocumentation.
|
According to the documentation, it's the amount of frames, not bytes.
In the example you linked to the values just happen to be the same because it's using 8-bit samples and one channel, and one frame of one channel 8-bit data is one byte.
|
So I byte shift a integer into 4 bytes of data.
```
img[4] = (imagewidth >> 24) & 0xFF;
img[5] = (imagewidth >> 16) & 0xFF;
img[6] = (imagewidth >> 8) & 0xFF;
img[7] = imagewidth & 0xFF;
img[8] = (imageheight >> 24) & 0xFF;
img[9] = (imageheight >> 16) & 0xFF;
img[10] = (imageheight >> 8) & 0xFF;
img[11] = imageheight & 0xFF;
```
Now how would I go about shifting it back to an integer. soimg[8]-img[11]back to a singleintorimg[4]-img[7]back to a singleint
|
```
imagewidth = img[4] << 24 | img[5] << 16 | img[6] << 8 | img[7];
imageheight = img[8] << 24 | img[9] << 16 | img[10] << 8 | img[11];
```
|
I have an application (for which I do not have the source code).
I know that it is designed to dynamically load a shared library, depending on the command line parameters.
I know which library it should be loading and I've set up LD_LIBRARY_PATH to the appropriate directory.
The application works on one server without any problems, but does not work on another.
I'm trying to figure out why and it would be helpful if I could confirm that the script is looking for the library that I think it is and if I could track where it is looking.
Are there any tools that could help me? I've been googling, but most of the information I'm finding is aboutlddwhich really only tells you about statically linked libraries.
This is in a Linux environment and the application and library are both written in C
Thanks
|
Usestrace. You will see the libraries being searched etc., which will help you figure out what is happening.
|
Using the pthread library in C, is it possible to send a SIGSTOP signal to an individual thread?
I want to ensure that even though I create N threads in a loop, all should start executing only when all of them have been created.
I ask because the man page forpthread_kill()mentions:
Signal dispositions are
process-wide: if a signal handler is
installed, the handler will be invoked
in the
threadthread, butif the disposition of the signal is "stop",
"continue", or "terminate", this
action will
affect the whole process.
|
Barriers (seepthread_barrier_init) are an even easier way to accomplish what you need.
|
I write a demo with libnet, but get an error when call the function:
```
libnet_error(LIBNET_ERR_FATAL, "libnet_open_link_interface: %s\n", errbuf);
```
The error is "error: ‘LIBNET_ERR_FATAL’ undeclared (first use in this function)".
my gcc command is: "gcc demo.clibnet-config --defines --cflags --libs", and run on ubuntu.
I want to know who got the same error before ?
|
It's the version problem, LIBNET_ERR_FATAL have been removed in 1.1!
|
I encountered this small piece of code inthis question, & wanted to know,
Can therealloc()function ever move a memory block to another location, when the memory space pointed to is shrinked?
```
int * a = malloc( 10*sizeof(int) );
int * b = realloc( a, 5*sizeof(int) );
```
If possible, under what conditions, can I expectbto have an address different from that ina?
|
It's possible forreallocto move memory on any call. True in many implementations a shrink would just result in the change of the reserved size in the heap and wouldn't move memory. However in a heap which optimized for low fragmentation it may choose to move the memory around to a better fitting location.
Don't depend onreallockeeping memory in the same place for any operation.
|
AFAIK: A http POST request is sent to apache, then piped through stdin and into a CGI program.
Does apache guarantee that the stdin stream will always have an EOF ?
|
EOF isn't a "character" or "marker" in the input; EOF is an error when attempting to read and not having more data available. Calls such asreadorfreadwill return this as an error, such as reporting less was read than was requested. (Thereisan EOF macro in C, but it's treated as an error code and isn't an actual character.)
EOF is signaled by the OS, not Apache, and even though Apache could pull some dirty tricks (such as keeping the stream open but never writing), it doesn't.
|
Simply, is
```
&someObject->someAttribute.someMember;
```
equivalent to
```
&(someObject->someAttribute.someMember);
```
or
```
(&someObject)->someAttribute.someMember;
```
or
```
(&(someObject->someAttribute)).someMember;
```
Or should you really put explicit parenthesis there just to be safe?
|
It is equivalent to:
```
&((someObject->someAttribute).someMember)
```
The->and.have equal precedence and are left-associative. The unary-&has lower precedence.
If you have very complex expressions, then you should certainly use parentheses to group things and clarify your code. This isn't particularly complex, though; it is quite common to see code like this in C and C++.
|
I'm testing one code provided from my colleague and I need to measure the time of execution of one routine than performs a context switch (of threads).
What's the best choice to measure the time? I know that is available High Resolution Timers like,
```
QueryPerformanceCounter
QueryPerformanceFrequency
```
but how can I translate using that timers to miliseconds or nanoseconds?
|
```
LARGE_INTEGER lFreq, lStart;
LARGE_INTEGER lEnd;
double d;
QueryPerformanceFrequency(&lFreq);
QueryPerformanceCounter(&lStart);
/* do something ... */
QueryPerformanceCounter(&lEnd);
d = ((doublel)End.QuadPart - (doublel)lStart.QuadPart) / (doublel)lFreq.QuadPart;
```
d is time interval in seconds.
|
I've never worked with a language that didn't provide for some form of memory management, and thus managed to get by without ever really groking pointers.
I can dabble inCI guess, as a result of coding inObjective-Cfor a little while.
|
Hmmm, maybe it's the single linked list.
Try it:create, populate, reverse, releasea single linked list
```
struct node {
int data;
struct node *next;
};
```
|
how to get the value of an integerx, indicated byx!, it is the product of the numbers 1 to x.
Example:5! 1x2x3x4x5 = 120.
```
int a , b = 1, c = 1, d = 1;
printf("geheel getal x = ");
scanf("%d", &a);
printf("%d! = ", a);
for(b = 1; b <= a; b++)
{
printf("%d x ", c);
c++;
d = d*a;
}
printf(" = %d", d);
```
|
how to get the som of an integer x, indicated by x!, is the product of the numbers 1 to x.
Did you meanfactorialof x ?
Changed = d*a;tod = d*binside the loop
|
When I run this bit of code through GCC I get this warning on the line where I set info to SDL_GetVideoInfo().
warning: initialization discards qualifiers from pointer target type
```
int main(int argc, char** argv) {
SDL_Init(SDL_INIT_EVERYTHING);
SDL_VideoInfo* info = SDL_GetVideoInfo();
int SCREEN_WIDTH = info->current_w;
int SCREEN_HEIGHT = info->current_h;
printf("hardware acceleration? %s\n", info->hw_available == 1 ? "yes" : "no");
printf("memory available in kilobytes: %d\n", info->video_mem);
SDL_Quit();
return 0;
}
```
Does anyone know how I can change the code so I can get around that warning?
|
Thedocumentationsays that the function returns aconst SDL_VideoInfo *, so change your code to:
```
const SDL_VideoInfo* info = SDL_GetVideoInfo();
```
Without theconst,infocould be used to change the value pointed to by it, but obviously, you can't do that.
|
I'm trying simple example -
```
#include <stdio.h>
int main(void)
{
printf("Content-type: text/html\n\n");
printf("<html><title>Hello</title><body>\n");
printf("Goodbye Cruel World\n");
printf("</body></html>");
return 1;
}
```
compiled and moved to apache docroot - but when i click on url - it comes as a popup and asks where to download/save this binary file? how to fix this?
|
Unfortunately, unless you already have other CGI scripts running in the same place, this is harder than just plopping a file somewhere - some stuff has to be configured in the web server to make it possible: apache settings, the.htaccessfile, permissions, and so on.
Make sure you read theApache Tutorial on CGIto be up to date with what needs to be configured.
|
I want to use my program like this:
```
./program -I /usr/include/ /usr/bin/ /usr/local/include/ ...
```
Where the switch can go on and on like in a var args list. How could I do that in C99? Preferably get a something likechar **args_listorchar *args_list[]that contains all of the things like/usr/includeand/usr/bin/.
|
The output of running the following code:
```
int main(int argc, char* argv[])
{
for (int i = 1; i < argc; ++i)
{
printf("%s\n", argv[i]);
}
}
```
Executed byprogram -I /usr/include/ /usr/bin/ /usr/local/include/
Output:
```
-I
/usr/include/
/usr/bin/
/usr/local/include/
```
Note that in the code example the initial index is1. This is because the first pointer in theargvvariable is the name of the program. In this case it would beprogram.
|
What happens in C when you create an array of negative length?
For instance:
```
int n = -35;
int testArray[n];
for(int i = 0; i < 10; i++)
testArray[i]=i+1;
```
This code will compile (and brings up no warnings with -Wall enabled), and it seems you can assign totestArray[0]without issue. Assigning past that gives either a segfault or illegal instruction error, and reading anything from the array says "Abort trap" (I'm not familiar with that one). I realize this is somewhat academic, and would (hopefully) never come up in real life, but is there any particular way that the C standard says to treat such arrays, or is does it vary from compiler to compiler?
|
It's undefined behaviour, because it breaks a "shall" constraint:
C99 §6.7.5.2:
If the size is an expression that is
not an integer constant expression...
...each time it is evaluated it shall
have a value greater than zero.
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:Variable length arrays in C++?
I am just curious, is there any particular reason why C++ does not allow variable length arrays?
|
Two reasons:
C++ is based on C89 (the C standard as published in 1989). VLAs were only introduced in C99.C++ hasstd::vector<>and a whole bunch of other containers, which is why I believe that C++ will never bother with VLAs. It already had them when VLAs were invented for C.
|
AFAIK: A http POST request is sent to apache, then piped through stdin and into a CGI program.
Does apache guarantee that the stdin stream will always have an EOF ?
|
EOF isn't a "character" or "marker" in the input; EOF is an error when attempting to read and not having more data available. Calls such asreadorfreadwill return this as an error, such as reporting less was read than was requested. (Thereisan EOF macro in C, but it's treated as an error code and isn't an actual character.)
EOF is signaled by the OS, not Apache, and even though Apache could pull some dirty tricks (such as keeping the stream open but never writing), it doesn't.
|
Simply, is
```
&someObject->someAttribute.someMember;
```
equivalent to
```
&(someObject->someAttribute.someMember);
```
or
```
(&someObject)->someAttribute.someMember;
```
or
```
(&(someObject->someAttribute)).someMember;
```
Or should you really put explicit parenthesis there just to be safe?
|
It is equivalent to:
```
&((someObject->someAttribute).someMember)
```
The->and.have equal precedence and are left-associative. The unary-&has lower precedence.
If you have very complex expressions, then you should certainly use parentheses to group things and clarify your code. This isn't particularly complex, though; it is quite common to see code like this in C and C++.
|
I'm testing one code provided from my colleague and I need to measure the time of execution of one routine than performs a context switch (of threads).
What's the best choice to measure the time? I know that is available High Resolution Timers like,
```
QueryPerformanceCounter
QueryPerformanceFrequency
```
but how can I translate using that timers to miliseconds or nanoseconds?
|
```
LARGE_INTEGER lFreq, lStart;
LARGE_INTEGER lEnd;
double d;
QueryPerformanceFrequency(&lFreq);
QueryPerformanceCounter(&lStart);
/* do something ... */
QueryPerformanceCounter(&lEnd);
d = ((doublel)End.QuadPart - (doublel)lStart.QuadPart) / (doublel)lFreq.QuadPart;
```
d is time interval in seconds.
|
I've never worked with a language that didn't provide for some form of memory management, and thus managed to get by without ever really groking pointers.
I can dabble inCI guess, as a result of coding inObjective-Cfor a little while.
|
Hmmm, maybe it's the single linked list.
Try it:create, populate, reverse, releasea single linked list
```
struct node {
int data;
struct node *next;
};
```
|
how to get the value of an integerx, indicated byx!, it is the product of the numbers 1 to x.
Example:5! 1x2x3x4x5 = 120.
```
int a , b = 1, c = 1, d = 1;
printf("geheel getal x = ");
scanf("%d", &a);
printf("%d! = ", a);
for(b = 1; b <= a; b++)
{
printf("%d x ", c);
c++;
d = d*a;
}
printf(" = %d", d);
```
|
how to get the som of an integer x, indicated by x!, is the product of the numbers 1 to x.
Did you meanfactorialof x ?
Changed = d*a;tod = d*binside the loop
|
When I run this bit of code through GCC I get this warning on the line where I set info to SDL_GetVideoInfo().
warning: initialization discards qualifiers from pointer target type
```
int main(int argc, char** argv) {
SDL_Init(SDL_INIT_EVERYTHING);
SDL_VideoInfo* info = SDL_GetVideoInfo();
int SCREEN_WIDTH = info->current_w;
int SCREEN_HEIGHT = info->current_h;
printf("hardware acceleration? %s\n", info->hw_available == 1 ? "yes" : "no");
printf("memory available in kilobytes: %d\n", info->video_mem);
SDL_Quit();
return 0;
}
```
Does anyone know how I can change the code so I can get around that warning?
|
Thedocumentationsays that the function returns aconst SDL_VideoInfo *, so change your code to:
```
const SDL_VideoInfo* info = SDL_GetVideoInfo();
```
Without theconst,infocould be used to change the value pointed to by it, but obviously, you can't do that.
|
I'm trying simple example -
```
#include <stdio.h>
int main(void)
{
printf("Content-type: text/html\n\n");
printf("<html><title>Hello</title><body>\n");
printf("Goodbye Cruel World\n");
printf("</body></html>");
return 1;
}
```
compiled and moved to apache docroot - but when i click on url - it comes as a popup and asks where to download/save this binary file? how to fix this?
|
Unfortunately, unless you already have other CGI scripts running in the same place, this is harder than just plopping a file somewhere - some stuff has to be configured in the web server to make it possible: apache settings, the.htaccessfile, permissions, and so on.
Make sure you read theApache Tutorial on CGIto be up to date with what needs to be configured.
|
I want to use my program like this:
```
./program -I /usr/include/ /usr/bin/ /usr/local/include/ ...
```
Where the switch can go on and on like in a var args list. How could I do that in C99? Preferably get a something likechar **args_listorchar *args_list[]that contains all of the things like/usr/includeand/usr/bin/.
|
The output of running the following code:
```
int main(int argc, char* argv[])
{
for (int i = 1; i < argc; ++i)
{
printf("%s\n", argv[i]);
}
}
```
Executed byprogram -I /usr/include/ /usr/bin/ /usr/local/include/
Output:
```
-I
/usr/include/
/usr/bin/
/usr/local/include/
```
Note that in the code example the initial index is1. This is because the first pointer in theargvvariable is the name of the program. In this case it would beprogram.
|
What happens in C when you create an array of negative length?
For instance:
```
int n = -35;
int testArray[n];
for(int i = 0; i < 10; i++)
testArray[i]=i+1;
```
This code will compile (and brings up no warnings with -Wall enabled), and it seems you can assign totestArray[0]without issue. Assigning past that gives either a segfault or illegal instruction error, and reading anything from the array says "Abort trap" (I'm not familiar with that one). I realize this is somewhat academic, and would (hopefully) never come up in real life, but is there any particular way that the C standard says to treat such arrays, or is does it vary from compiler to compiler?
|
It's undefined behaviour, because it breaks a "shall" constraint:
C99 §6.7.5.2:
If the size is an expression that is
not an integer constant expression...
...each time it is evaluated it shall
have a value greater than zero.
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:Variable length arrays in C++?
I am just curious, is there any particular reason why C++ does not allow variable length arrays?
|
Two reasons:
C++ is based on C89 (the C standard as published in 1989). VLAs were only introduced in C99.C++ hasstd::vector<>and a whole bunch of other containers, which is why I believe that C++ will never bother with VLAs. It already had them when VLAs were invented for C.
|
What is the Delphi equivalent of
```
unsigned char** '
```
in C
i'm not sure if its a pointer to an array or a pointer to a pointer or if the two things are the same in C.
|
EDITIn C both pointer to an array and pointer to a pointer have different meaning to the compiler (thanks caf).
In C arrays are simply block of memory. There is no such function likeLength(array),Low(array)orHigh(array)that you can use on Pascal arrays. For practical purpose to Pascal programmers C arrays can be usually ported to Pascal pointers, especially on function calls to various API.
If we assume thatusigned charcan be translated tobytein Delphi, thenunsigned char *can be translated to^bytethat is usually done viatypedeclaration that can look like:
```
type
PByte = ^byte;
PPByte = ^PByte;
```
If you are trying to convert some C code, especially.hheader file then look atheadconv.
|
While reading about printf(),I found that it can print numbers as positive or negative as desired by the user by following code(for -).But the code doesnt work and the output is a positive value.Please mention where the error is.Thanks
```
#include<stdio.h>
int main()
{
printf (" %-d\n", 1977);
return 0;
}
```
|
From your comments it looks like you misreadthis page. The-and+specifiers do two completely different things, and neither does what you think '-' should do.
As others have noted,-does left justification. The+specifier prints positive numbers with a leading plus sign (and negative numbers still get a leading minus sign):
```
printf("%d %d %+d %+d\n", -10, 10, -10, 10);
```
outputs:
-10 10 -10 +10
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:Can you write object oriented code in C?
Hi, can someone point me to a tutorial explain me how OOP concepts can be implemented in ANSI C:
virtual functionsinheritancebest practice
A book about OOP programming ANSI C would be great too.
|
Here is the link of a book on this topic:http://www.planetpdf.com/codecuts/pdfs/ooc.pdf(Object Oriented Programming in Ansi-C - exacty what you were looking for).
Good luck and have patience. Writing OOP in C is not an easy task, but can be somewhat rewarding if you like extreme things !
Another starting point will be to check GObject:http://library.gnome.org/devel/gobject/and as @unwind saidGTKis a good example of how to use OOP concepts in C. You can also take atGLib, is a nice library that will certainly make your C programming life a lot more easier, it is programmed in OOP manner, and as a plus is portable!
|
Is this possible? The idea is typing a password and it being translated to asterisks on the fly- pretty much like a password field on HTML. I've written this code, but it converts the input AFTER the user presses enter, not while he/she is typing.
```
#include <stdio.h>
#include <string.h>
#include <iostream>
int main()
{
char password[11]; int i, j;
printf("Enter the password : ");
gets(password);
system("cls");
int str_len = (int)strlen(password);
printf("Enter the password : ");
for(i = 0;i<2;i++)
{
printf(" ");
for(j=0;j<str_len/2;j++)
{
printf("*");
}
}
system("PAUSE>nul");
}
```
|
I don't think it is possible using standard io. You need a library for more advanced text user interface like ncurses.
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:“C subset of C++” -> Where not ? examples ?
I'm aware that C++ is not a strict superset of C. What language features prevent C++ from being a superset of C?
|
The elephant in the room: the following is valid C but not valid C++.
```
int typename = 1;
```
Substitute your favorite C++ reserved word.
|
```
size_t pixelsWidth = (size_t)bitmapSize.width;
```
Or is it totally fine to do without the casting to size_t? bitmapSize is of type CGSize...
|
You should use the proper type, which is probably CGFloat. size_t is something int'ish and inappropriate.
|
This question already has answers here:How to get the return value of a program ran via calling a member of the exec family of functions?(6 answers)Closed9 years ago.
I have this c code:
```
if(fork()==0){
execl("/usr/bin/fsck", "fsck", "/dev/c0d0p1s0", NULL);
}
```
it callsexeclto runfsckfor checking the filesystem/dev/c0d0p1s0.
My question is: how can I get the return value offsck?
I need the return value offsckto check whether the file system is consistence or not.
Thank you.
|
Have the parent process wait for the child to exit:
```
pid_t pid = fork();
if (pid == -1) {
// error, no child created
}
else if (pid == 0) {
// child
}
else {
// parent
int status;
if (waitpid(pid, &status, 0) == -1) {
// handle error
}
else {
// child exit code in status
// use WIFEXITED, WEXITSTATUS, etc. on status
}
}
```
|
Could someone provide me an example of utilizing SECURITY_DESCRIPTOR inInitializeObjectAttributes()? I plan to use them with NtCreateKey(). I couldn't find any example on the Internet.
Thanks in advance.
|
The last parameter ofInitializeObjectAttributes()can be just well documentedSECURITY_DESCRIPTOR. You can use for exampleConvertStringSecurityDescriptorToSecurityDescriptorto convertSecurity Descriptor String FormattoSECURITY_DESCRIPTOR. You can createSECURITY_DESCRIPTORwithout usage ofsecurity descriptor definition language (SDDL).
|
I have a socket() function call in my code.(using C language):
socket(AF_INET, SOCK_STREAM, 0))
I want that it should result in error.(INVALID_SOCKET)
Do we have some way out so that above function call results in error.
Like stopping some services,etc
|
Since you say this is in your code, you could define your own implementation ofsocketthat always returns INVALID_SOCKET:
```
int socket(int domain, int type, int protocol)
{
return INVALID_SOCKET;
}
```
If you link with the object file that defines your version of socket before linking with the real version, the linker will send all calls tosocketto your implementation.
|
How is the debug information organized in a compiled C/C++ program?
What does it contain?
How is the debug information used by the debugger, e.g. gdb, and how can I read the debug information better than nm or objdump?
|
The debugging information depends on the operating system -gdbuses whatever the native format is. On many UNIX-like systems, debugging information is stored inDWARFformat. You can uselibdwarfanddwarfdumpto examine this information.
EDIT: On Linuxreadelf -w a.outwill print allDWARFdebug info contained in the executable (also works for shared libraries and object files).
|
Is there any way to easily limit a C/C++ application to a specified amount of memory (30 mb or so)? Eg: if my application tries to complete load a 50mb file into memory it will die/print a message and quit/etc.
Admittedly I can just constantly check the memory usage for the application, but it would be a bit easier if it would just die with an error if I went above.
Any ideas?
Platform isn't a big issue, windows/linux/whatever compiler.
|
Read the manual page forulimiton unix systems. There is a shell builtin you can invokebeforelaunching your executable or (in section 3 of the manual) an API call of the same name.
|
What libraries for C do I need to play a wav file on a Win32 system?
And what is the code to use those libraries?
|
Use the Win32 API:PlaySound
Include library:Winmm.libHeader include:Mmsystem.h(includeWindows.h)Example:
```
PlaySound(TEXT("recycle.wav"), NULL, SND_FILENAME);
```
|
Given:
```
struct objStruct {
int id;
int value;
};
typedef struct objStruct Object;
```
Is there a shortcut to allocate and initialize the object, something like a C++ constructor?It could even be a preprocessor macro. Whatever makes the code shorter and more readable than this:
```
Object *newObj = malloc(sizeof(Object));
// successful allocation test snipped
newObj->id = id++;
newObj->value = myValue;
```
|
In C I typically create a function in the style of a constructor which does this. For example (error checking omitted for brevity)
```
Object* Object_new(int id, int value) {
Object* p = malloc(sizeof(Object));
p->id = id;
p->value = value;
return p;
}
...
Object* p1 = Object_new(id++, myValue);
```
|
e.g. one has a couple of arrays of ints or floats and a few integers to store. Is there a simplistic way to save them for later reloading without having to write a data format from scratch etc.?
|
netcdf (simpler interface)hdf5 (more powerful)
they are not simple, however few hours investment is worth it
|
The template and cppIntegration examples in the CUDA SDK (version 3.1) use Externs to link function calls from the host code to the device code.
However, Tom's commenthereindicates that the usage of extern is deprecated.
If this the case, what's the correct structure for a CUDA project such as the template example or cppIntegration example?
|
Depends what your host code is. If you end up mixing C and C++ you still need the externs. For details seethis guide.
Update: the content from the above link has been moved [here] (https://isocpp.org/wiki/faq/mixing-c-and-cpp).
|
What is going on here?
```
#define CONSTANT_UNICODE_STRING(s) \
{ sizeof( s ) - sizeof( WCHAR ), sizeof(s), s }
.
.
.
.
UNICODE_STRING gInsufficientResourcesUnicode
= CONSTANT_UNICODE_STRING(L"[-= Insufficient Resources =-]");
```
This code is working.
I need to see the pre-processors expansion,
and whats up with commas in macro definition.
|
UNICODE_STRINGis defined in<winternl.h>as a type that has two sizes followed by a pointer to a string.
```
typedef struct _UNICODE_STRING {
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
} UNICODE_STRING;
```
The commas in the macro separate the values for the fields in the structure.
|
TheC-faqsays that the code:
```
int i = 7;
printf("%d\n", i++ * i++);
```
prints 49. Regardless of the order of evaluation, shouldn't it print 56?
When I ran this code on my Turbo C 3.0 compiler it gave me the output of 56. Why is there a contradiction?
|
There is no contradiction. The question was worded from a user perspective, and if you carefully read the answer, you will find the remark
The behavior of code which contains
multiple, ambiguous side effects has
always been undefined.
So it might print 49, or 56. Undefined behavior is, after all, undefined. This is why there is no real contradiction. You might want to brush up your understanding of what are called sequence points.
|
Are the following equivalent in C?
```
// #1
struct myStruct {
int id;
char value;
};
typedef struct myStruct Foo;
// #2
typedef struct {
int id;
char value;
} Foo;
```
If not, which one should I use and when?
(Yes, I have seenthisandthis.)
|
The second option cannot reference itself. For example:
```
// Works:
struct LinkedListNode_ {
void *value;
struct LinkedListNode_ *next;
};
// Does not work:
typedef struct {
void *value;
LinkedListNode *next;
} LinkedListNode;
// Also Works:
typedef struct LinkedListNode_ {
void *value;
struct LinkedListNode_ *next;
} LinkedListNode;
```
|
My professor and a couple of students are arguing about whetherargvis null terminated or not. My friend wrote a small program and it printed outnullbut another kid said that he is probably simply reading into blank memory. Can someone solve this discussion?
|
From the Standard:
5.1.2.2.1 Program startup...-- argv[argc] shall be a null pointer.
So, yes; argv is null terminated
|
Here's some example code to give an idea of what I want.
```
int regular_function(void)
{
int x,y,z;
/** do some stuff **/
my_api_call();
return x;
}
...
void my_api_call(void)
{
char* caller = get_caller_file();
int line = get_caller_line();
printf("I was called from %s:%d\n", caller, line);
}
```
Is there a way to implement theget_caller_file()andget_caller_line()? I've seen/used tricks like#defineingmy_api_callas a function call passing in the__FILE__and__LINE__macros. I was wondering if there was a way to access that information (assuming it's present) at run time instead of compile time? Wouldn't something like Valgrind have to do something like this in order to get the information it returns?
|
If you have compiled your binary with debug symbols, you may access it using special libraries, likelibdwarffor DWARF debug format.
|
```
/* strchr example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "This is a sample string";
char * pch;
printf ("Looking for the 's' character in \"%s\"...\n",str);
pch=strchr(str,'s');
while (pch!=NULL)
{
printf ("found at %d\n",pch-str+1);
pch=strchr(pch+1,'s');
}
return 0;
}
```
How would I index the str so that I would replace every 's' with 'r'.
Thanks.
|
You don't need to index the string. You have a pointer to the character you want to change, so assign via the pointer:
```
*pch = 'r';
```
In general, though, you index using[]:
```
ptrdiff_t idx = pch - str;
assert(str[idx] == 's');
```
|
Is it possible to have the array subscript before the variable name in declaration?
For example, is it possible to have
```
char [10]data;
```
where the intended declaration is:
```
char data[10];
```
I know that this might be stretching it a bit too much, but I have the variable type defined using#define, which I need to change from int to char[10] type.
So, could I just use#define TYPE char[10]instead of#define TYPE int? Or is there a better way to achieve this?
Edit:
Must I use 2 different #define statements like this?
```
#define TYPE char
#define SIZE [10]
```
and then use:
```
TYPE data SIZE;
```
|
You might want to consider using a typedef for this:
```
typedef char TYPE[10];
```
|
That is, why doesunsigned short var= L'ÿ'work, butunsigned short var[]= L"ÿ";does not?
|
L'ÿ'is of typewchar_t, which can be implicitly converted into anunsigned short.L"ÿ"is of typewchar_t[2], which cannot be implicitly converted intounsigned short[2].
|
For debugging reasons, how can one in a C program print some memory address?
For instance, how should I do to print the content of address 0x611268 in form of a 4 byte float?
I know I could use a debugger, but I mean, to print out in screen.
|
More correctly,printf("Value = %f\n", *((float*)0x611268));
Of course this assumes the address you've given is in the address space of the process running theprintf.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.