question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
Put on your c++ ninja voodoo gloves.
We purchased a 3rd party library to use in our iOS app. There are 2 versions of that library, so let's call thembull_frog_noises.aandtoad_frog_noises.a.
The company never imagined that someone would want to makebothfrog noises ina singleapp, so each library offers thesame method ... |
I would try using a hex editor to manually modify one of those libraries so that every instance of MAKE_FROG_NOISE was replaced with MAKE_TOAD_NOISE. You would have to be extremely careful to make only that one change. You can only replace bytes. Don't insert or delete anything. And don't change anything else in the ... |
I do open large files with fopen under c with a kind-of observed folder logic.
I'd like to fopen (or at least to fread) the file as soon as it has been copied completely to my observed folder.
How can i detect if another process is writing to a file?
Is that possible with standard-c?
Thanks
|
There's no way to do it with standard C. The best you can do is heuristically notice when file stops changing, e.g. read the last few blocks of the file, sleepnseconds, then read the blocks again and compare against the previous read. You could also try just watching the end of file seek pointer to see when it stops... |
Newbie to C. I'm writing an ANSI C program (on Linux using gcc 4.4.6) and need to know how to initilize a numeric array, such as int or double, where the length of the array is determined when the program is run?
Does ANSI C allow one to declare variable, execute some code (wherein the length is determined), then dec... |
You need to allocate the memory for the array and free it after you are done.
Seemallocandfreeand get one of the beginner books listedhere. Attempting to write C without a solid foundation ends in blood, tears and segfaults. Think of the children. Don't do it.
Example to get you started with shooting yourself in the... |
In a C program, how do I tell the linux kernel to TRIM a block on a SSD disk?
I suppose I have toopen()the device andfcntl()it something, but what?
It needs to be generic (i.e. work with different SSD disks)
Note: there is no ext4 filesystem on the device, just raw data.
|
You would send itIOCATADELETE. Something like this:
```
//header - may already be defined
#define IOCATADELETE _IOW('a', 104, off_t[2])
//code
int fd = open("/dev/abc", O_RDWR | O_DIRECT);
off_t ioarg[2];
ioarg[0] = 0; //block number
ioarg[1] = 0; //size
ioctl(fd, IOCATADELETE, ioarg);
close(fd);
```
|
Does someone know how to write a program in C with the verbose option (the option to choose if messages are printed or not) in a nice way.
I mean, not writing an if(verbose) for each printf in the code.
Is there a more elegant solution?
|
Just use a (variadic) macro / vararg function that tests a flag before calling something like vfprintf.
```
/* Crude example. */
void my_log(char *format, ...)
{
va_list args;
if (!ok_to_log)
return;
va_start(args, format);
vprintf(format, args);
va_end(args);
}
```
EDIT As requested
Ho... |
I'm having some trouble with VBO's with my project.
note: The code worked perfectly before trying to use VBO's.
Here's the error:http://pastebin.com/6x7YWtgc
Here's the gdb backtrace:http://pastebin.com/zn3aN43b
My glut+glew initialization code and some relevant code and data structures:http://pastebin.com/xEEUc0ix... |
From what I can see within your code, you have enabled a vertex, normal, and texture coordinate array:
```
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
```
However, you only set a pointer to the vertex array:
```
glVertexPointer(3, GL_FLOAT... |
I have a little problem, I need to make directory from my c code or c++, doesn't matter.
But directory name must contain characters like ':', ' ','.' in general current time,
when I try to create withmkdir()function I get EINVAL error, but fromsystem("mkdir ...")everything is ok.
How can I solve this problem?
Thank ... |
Different filesystem formats have different rules about what is and is not a valid character. Forext2and its descendants, A file name may contain any character except for'/'or'\0'.
For FAT filesystem and its descendants, the list of invalid characters is larger, and includes':'.
Check to see what filesystem format ... |
In a terminal I get this:
```
manu@work:ulimit -s
manu@work:8192
```
Now in a Makefile, I have
```
test:
echo `ulimit -s`
```
An running make in the same terminal gives:
```
manu@work:make test
manu@work:unlimited
```
Why ? Does the make process changes it's own threads stack size ?
|
setrlimit(R_LIMIT_STACK, ...);Alternatively, Linux also providesprlimitwhich can act as eithergetlimit,setrlimit, or both.
|
hi i am using lxscoket in iPhone to create sockets for iPhone. but here i am unable to find the last error which occurred.i am trying to use [err code] to find the error but it is not giving the error. so can any one please guide me in this.......
|
using theerrnopresent in<sys/errno.h>we can find the last error.
|
I have a library that has several options defined as this:
```
#define shouldShowToolbar YES
#define shouldAlignToLeft YES
etc..
```
and I'm looking for a way to actually replace those from outside (without modifying the library, because the future updates will break it). Is it possible, or am I doomed to change the... |
There is#undef
```
#include "library_header.h" /* Which defines the macro. */
#undef shouldShowToolbar /* You undef it. */
#define shouldShowToolbar NO /* If you want, you can redefine it. */
```
http://gcc.gnu.org/onlinedocs/cpp/Undefining-and-Redefining-Macros.html
|
If a constant is declared like this
```
const char *http_range;
```
Then how can I write the content or the value of it in a text file? Could you please show me with syntax?
|
First, that is not "a constant". It's a pointer to constant character data, i.e. a pointer to a read-only string. You can change the pointer, but you can't change the data it's pointing at. For example:
```
FILE *out;
const char *http_range = "Accept: text/*;q=0.3, text/html;q=0.7";
if ((out = fopen("textfile.txt", ... |
I learned that Xcode can compile c code, that means can we write whole program in c?
|
Yes. Objective C is a strict superset of C. This means that any C code is valid also in Objective C. But most of framework APIs are in Objective C, if you need to call these, you will have to include Objective C code as well. However standard C libraries are supported and even for 2D graphics there are Cocoa classes i... |
Very simple example - hoping for a simple solution:
```
char x[7];
if(fgets(x,5,stdin))
printf("y");
else
printf("n");
```
I can't seem to get it to print "n" when I input more than the byte limit - is there any simple way I could enforce it or catch when it's surpassed?
As a side question, what example inp... |
fgetswill return 0 when it fails, so to get 'n' as an output, you'd use control-D or control-Z (or whatever your OS uses to indicate end of input) without entering anything else first.
To detect when more has been entered than you've left room to read, check whether the last character you read was a new-line. If it i... |
I'm a beginner in C and I have code like this :
```
#include <stdio.h>
main()
{
int i;
int ndigit[10] = { [9] = 5 };
printf("%d\n",++ndigit['9']);
}
```
This prints the value something like this :
```
-1074223011
```
But when I change the statement to:
```
++ndigit['9'-'0']
```
It is correctly printi... |
If you want to access the 10th element in an array, you do:
```
array[9]
```
If you want to access the element at the index which has the value of the character constant for the number9+ 1, you do:
```
array['9']
```
Due to the way ASCII (and all other character encoding schemes used by C, see Wiz's comment) is de... |
I have atrace()macro I turn on and off with another macro, e.g.
```
#ifdef TRACE
#define trace(x) trace_val(x, 0)
#else
#define trace(x) 0
#endif
```
This generateswarning: statement with no effectfrom gcc when I calltrace()withTRACEundefined. After a little searching I found that changing
```
#define trace... |
The cast to void makes it clear that the programmer intends to throw the result away. The purpose of the warning is to indicate at that it's not obvious that the statement has no effect and thus it's useful to alert the programmer to that in case it was unintentional. A warning here would serve no purpose.
|
If you have a C pointer which was defined in a method and are trying to return it from an object method in Objective C, what do you place as the return object type for the method?
For example, I am using code that converts a UIImage into an RGBA image map (as seenhere) - but the code stores a C pointer to the memory ... |
I don't know why is this related to C#, however Objective-C is a superset of C, thus every C syntax is also a valid Objective-C syntax.
Just placevoid*as return type.
|
I need to be able to convert case in strings, so that"Hello"becomes"hello". Ultimately, I need to compare them.
How would I convert:
```
char *string = "HEllO";
```
to the string"hello"?
|
First, your string is not declared properly, it should be:
```
char *string = "Hello";
```
Now, to convert to lowercase, try this:
```
char *lowercase(const char *str)
{
int length = strlen(str);
char *dup = malloc(length + 1);
strcpy(dup, str);
for (int i = 0; i < length; i++)
{
dup[i... |
Newbie to C. I'm writing an ANSI C program (on Linux using gcc 4.4.6) and need to know how to initilize a numeric array, such as int or double, where the length of the array is determined when the program is run?
Does ANSI C allow one to declare variable, execute some code (wherein the length is determined), then dec... |
You need to allocate the memory for the array and free it after you are done.
Seemallocandfreeand get one of the beginner books listedhere. Attempting to write C without a solid foundation ends in blood, tears and segfaults. Think of the children. Don't do it.
Example to get you started with shooting yourself in the... |
I have a library that has several options defined as this:
```
#define shouldShowToolbar YES
#define shouldAlignToLeft YES
etc..
```
and I'm looking for a way to actually replace those from outside (without modifying the library, because the future updates will break it). Is it possible, or am I doomed to change the... |
There is#undef
```
#include "library_header.h" /* Which defines the macro. */
#undef shouldShowToolbar /* You undef it. */
#define shouldShowToolbar NO /* If you want, you can redefine it. */
```
http://gcc.gnu.org/onlinedocs/cpp/Undefining-and-Redefining-Macros.html
|
List of available LLVM passes are desribed here. I am interested in knowing which passes are included for different optimization levels. For example, for -O2 which passes are included. Is there any site or document which provides that information.
|
It's visible inPassManagerBuilder.cppfile. Take a look at populateModulePassManager method where OptLevel is integer that follows -O option.
|
In C, semicolons (;) are used to indicate the end of the statement. Why do#includelines not need a semicolon?
|
#include(and all other lines beginning with#like#define) is part of thepreprocessor. This is actually a separate programs that runs before the main compiler and does things likeincludefiles into the source and macro expansion.
|
I have a C struct with about 17 membersstruct settings currentProfileand would like to initialise it all members to zero. (I have tried this both with the uber-correct struct syntax and with typedef syntax)
To set all members to zero I usecurrentProfile = {0}
at this line the compiler gives the erroExpected an expre... |
You are doing an (invalid) assignment not an initialization.
To initialize your struct object with all members set to0:
```
struct settings currentProfile = {0};
```
To set all the members of the struct object to0after its declaration:
```
memset(¤tProfile, 0, sizeof currentProfile);
```
|
I am writing a web-spider program with C. Now I am given a url's list, and first I need to get the server IP address using function:getaddrinfo, and then ridiculous thing happended:
In the url's list there are about 4,000,000 url's, the first about 6,000 url's are processed very well, and then suddenly all of the url... |
You may be hitting some sort of rate limiting in your DNS server.
As with all network problems, run Wireshark: check if the DNS requests which are failing are actually being sent, and if so, what reply they're getting.
|
hi how to use the valid part of an xml present inside a broken xml
Ex: <nodea><nodeb>DATA</nodeb<nodec> DATA </nodec>
at above since the nodea is not getting closed so this is a broken xml,but the nodeb & nodec are the valid Xmls present inside nodea. so can i retrive the data inside them or not using libxml2.
|
You have to fix the file by a heuristical hack before you parse it.
```
$ cat broken.xml
<nodea>
<nodeb>DATA</nodeb
<nodec> DATA </nodec>
$ < broken.xml sed 's%</nodeb[^>]%</nodeb>%'
<nodea>
<nodeb>DATA</nodeb>
<nodec> DATA </nodec>
```
|
does any one know if, for example, I'm writing in c++ the following code:
```
int a;
void *ptr = &a;
ptr = (char *)ptr + 1; //<-- this is the interesting line;
```
Does the(char *)only tells the compiler how to address this variable?Or does it actually add more calculations in run time?
Thanks.
|
In this case, no extra calculations are done.
However, there are some cases where a cast is technically a conversion, mostly with numeric input. For example the following could introduce runtime code (provided it is not optimised out, which in a small example like this you'd expect it to be):
```
int x = 42;
double ... |
I have a problem in C.
```
#include<stdio.h>
int main()
{
int a = 10, b = 0, c = 7;
if (a ? b : c == 0)
printf("1");
else if (c = c || a && b)
printf("2");
return 0;
}
```
This code prints 2 but I think a?b:c returns b=0 and 0==0 returns 1. Can you explain the code?
|
The conditional operator (?:) has one of the lowest precedences. In particular it is lower than==. Your statement means this:
```
if(a ? b : (c == 0)) { ... }
```
Not this:
```
if((a ? b : c) == 0) { ... }
```
|
I want to have a large 2 dimensional array such like
```
int myArray[10000][2];
```
I was told that the array built in such way is not appropriate, and should use malloc to build in heap. Could someone show me how to accomplish this? thanks!
|
```
#include <stdlib.h>
```
//alloc
```
int **vv = malloc(2 * sizeof(int *));
for(int i = 0; i < 2; i++)
vv[i] = malloc(10000 * sizeof(int));
```
//free
```
for(int i = 0; i < 2; i++)
free(vv[i]);
free(vv);
```
|
i have used libxml2.Here when i am getting an XML data as a string i am unable to check whether it is a valid xml or a broken xml.so can anyone let me know how to check for the validation of xml in c using libxml2 or can suggest any more way to check for the validation.
|
Have you tried theW3C Validator?
|
I want to create more or less portable (stand-alone, no install, WinXP to Win7) Win32 forms application in Visual Studio 2010. When I create a new project, it appears that the only way I can do it is if I use .NET/CLR, which makes me think it will beveryunportable.
What is the preferred way of creating such apps?
|
Depending on what you mean with portable. An .NET application will function on all versions of Windows that runs the correct version of .NET (even other OS'ses in some caseshttp://www.mono-project.com/Main_Page). You will only have a dependency of a hudge framework, thatI thinkmost people running Windows have by now.
... |
What would perror() be in the kernel? I can't tell what the error codes are from the error values ,i.e -22 alone.
|
The Linux kernel just uses negated errno codes as a convention. So look inasm-generic/errno-base.horasm-generic/errno.hand find...
```
#define EINVAL 22 /* Invalid argument */
```
This can happen if you passNULLto a function that doesn't acceptNULL, for example. It depends on the function.
|
The applicable code is below, as is the exact error.
```
sd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
if ( setsockopt( sd, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on) ) < 0 )
{
printf("%s\n", strerror(errno));
}
if ( setsockopt( sd, IPPROTO_IP, IP_DF, &on, sizeof(on) ) < 0 )
{
printf("%s\n", strerror(errno));
... |
IP_DFis a packet flag, not a socket option. Valid socket options are given in theip(7)man page.
|
In gcc you can declare a thread local variable, for example, as shown below.
```
__thread long thread_local_variable;
```
Also, in gcc you can specify a variable to use a certain register, for example, as shown below.
```
long register_variable asm ("r15" );
```
I want to combine these two concepts, that is, I wan... |
You don't need to do anything special. Your example:
```
long register_variable asm ("r15" );
```
is already declaring a thread-local variable, merely due to the fact that each thread has its own set of register values.
There is no possible way to make GCC's global register-storage variables shareable between threa... |
i want to convertint to char* in C without usingitoa()function.
Because on my Linux Systems iitoafunction is not there. i am using this code which i found fromhere
I want to run this function on Embedded devices also which are using Linux.
So i am looking for without use ofitoa.
I dnt want to usesprintfalso becaus... |
Thing issnprintfis the perfect function for this:
```
char str[LEN];
snprintf(str, sizeof(str), "%d", num);
```
|
I have a C program which has always used hard coded define statements for a few settings. Example...
```
#define TRIGGER_TIMEOUT 50000
```
This has worked just fine. Now, this setting is to become adjustable. Example...
```
g_ulTriggerTimeout = ReadEEPROM(TRIGGER_TIMEOUT_OFFSET);
```
If persistent storage is detec... |
This is IMHO one of those cases where bending the rules is ok.
```
const int g_ulTriggerTimeout; //declare somewhere making sure it is in a writable section (see comment below from undur)
/* later */
//just for this assignment make it modifiable
*((int*) &g_ulTriggerTimeout) = ReadEEPROM(TRIGGER_TIMEOUT_OFFSET);
``... |
I'm converting a code from C to Delphi, but I'm stuck on the last line of this code:
```
BOOL is_match = FALSE;
unsigned int temp_val;
unsigned int prev_val = 0;
is_match = (temp_val == val);
```
I can only convert this much:
```
var
is_match: boolean;
temp_val: cardinal;
prev_val: cardinal;
begin
is_m... |
is_match := temp_val = val;
At any rate, I hope the code above is just a small excerpt of the real code, becausetemp_valis undefined at the time you compare it withval.
|
I have a c source file in which one of the method is defined as follows:
```
void QDECL prettyPrintf(int level) {
////// some code.
}
```
I would like to know what is QDECL.In this case, is it returning QDECL type? As far as my little knowledge in C, a 'void' does not return anything.So, is it a legal statement?... |
QDECLis probably a preprocessor macro that resolves to acalling conventionhint (e.g.__cdeclor__stdcall); This defines how parameters are pushed onto and cleaned up in the call stack, but it does not change the return type of the function. It is mainly used for interoperability when using libraries that use a different... |
is it to possible to get data from grayscale png with fopen and then convert it to integer numbers corresponding to grayscale?
```
FILE *fr;
int ch;
fr = fopen( "file_name.png", "rb" );
while ( (ch=fgetc(fr)) != EOF )
printf( "%d", ch );
fclose( fr );
```
|
Not that easily, you can read about the file format at for example wikipedia:
http://en.wikipedia.org/wiki/Portable_Network_Graphics
I think your best option is to use some library like FreeImage to load the images.
|
I'm looking for an open source library to detect the language used in an audio file, such as a wav file. After some searches I found Thishttp://sourceforge.net/projects/marf/files/Applications/%5Bg%5D%20LangIdentApp/from MARF ( Modular Audio Recognition Framework).. Someone had already use it?
|
CheckCMU Sphinx Open Source Toolkit For Speech Recognitionthis project is quite active and in googles summer of code 2012.
|
I always thoughtcopy_to_userwas necessary when the kernel writes to users via procfs.
I forgot to do it once though (and I usedsnprintf) and everything was working fine. Now that I noticed it, I have been searching. I foundthis linkthat doesn't saycopy_to_useris needed even though for the other section (kernel readin... |
Always usecopy_from_userandcopy_to_userwhen dealing with user space pointers. Even if simplememcpysometimes works for you there are situations where it can fail. Seethisthread for the information.
Speaking aboutprocfsit's necessary to take into account that it use a little trick with kernel memory preallocation. Seet... |
in C, if I declare a static variable inside a local strucutre, where does the static variable get placed ?
Since the struct is in the stack, will the static variable also be in the stack ?
|
If I declare a static variable inside a local strucutre
In current Cthe keywordstaticis meaningless inside a structure. You should get an error from the compiler.
If by "static" you mean "not allocated using malloc": the member of a structure is always stored in the same place as the rest of the structure. If said... |
This is an Amazon interview Question.I have solved this problem in O(n) using dynamic
programming.But I want to know can there be more optimization thanO(n)
for e.g. suppose below is the array
```
3 7 1 4 2 4 returns 4
5 4 3 2 1 returns Nothing
4 3 2 2 3 returns 1
```
This is the code i have writtenCode
|
Lets say you've gotint A[N].
```
int res = -1;
int min_value = A[0];
for(int i=1; i<N; i++) {
// A[i] - A[j] is maximal, when A[j] is minimal value from {A[0], A[1],.., A[i-1]}
res = max(res, A[i] - min_value);
min_value = min(min_value, A[i]);
}
return res;
```
Complexity O(N).
You need to examine N el... |
I'm trying to convert a FOR loop from C to Delphi, but I'm with some doubts:
I know this code in C:
```
for (i = 0; i < mb->size; i++)
{
//...
}
```
is like this in Delphi:
```
for i := 0 to mb.size do
begin
//...
end;
```
But how is this C code:
```
for (i = ... |
You cannot use a for in delphi to do this because the variable used to iterate cannot be modified.
So this code
```
for (i = 0; i < mb->size; i+= mb->data_size)
```
can be written using a while
```
i:=0;
while (i<mb.size) do
begin
// do something
Inc(i, mb.data_size);
end;
```
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:When you exit a C application, is the malloc-ed memory automatically freed?
Pretty much the title. Do (modern) OSs automatically reclaim heap-allocated memory on program termination? If so, is freeing the memory astrict mustor more of ajus... |
When an application terminates, all memory will be reclaimed by the OS. The reason people preach memory management techniques is because so long as the app isrunning, any memory it's asked for will remain in its posession (even if it's no longer being used). Unless, of course, you were nice enough to callfree.
|
I am trying to write a multi-threaded program in which I need to call the function crypt. But the compiler throws this warning. Also it doesn't recognize crypt_data as well. Any ideas?
|
You need to include appropriate header file. In this casecrypt.h
```
#include <crypt.h>
```
|
I have the following C code:
```
typedef void (*mycallback) (char buf[128]);
void take_callback(mycallback cb)
{
}
```
I've written the equivalent Ruby FFI declarations as below (following advice for structs onFFI wiki):
```
callback :mycallback, [[:char, 128]], :void
attach_function :take_callback, [:mycallback]... |
Arrays aren't passed by value in C -- they're passed as pointers to the first element, so:pointer(or whatever is ordinarily used forchar *) should be correct.
|
Right now I'm doing as follow:
```
uint8_t ManualFlow = 40; // 0 -> 255 Unsigned Char
uint24_t ME; // 0 -> 16777215 Unsigned Short Long
ME = (uint24_t) ManualFlow*10; // Have to make this hack otherwise malfunction in calculation
ME /= 6;
ME *= (80 - 60);
ME /= 100;
ME *= 414;
```
The end result:
```
40*10 = 4... |
You may want to look at fixed point arithmetic:
http://en.wikipedia.org/wiki/Fixed-point_arithmetic
And Technical Report 18037 from WG14 (the last version ISO/IEC TR 18037:2008 is unfortunately not free):
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1169.pdf
|
I would like to ask you what's the most efficient way for checking user's input in C. I want the user to enter a 4 digit integer. How can I make sure that the user has entered exactly 4 digits and no letters?
|
One way:
1) read asstringorchar*
2) check each char falls within 49-58 ASCII range.
Finally, convert intointusingatoi()(or atol() in case of long) if there are only four chars in the string and satisfy (2)
|
So, the question might seem strange, but let's say that I compile:
```
int main(void)
{
int x = 3;
int y = 4;
int z = x + y;
}
```
Is it possible to make the CPU run just that? How? For example, would this allow me to write to the monitor? (If I remember it correctly, there are places in memory in which... |
In the case of your program, it does not rely on any operating system services other than getting it started. If it were to additionally do input or output, it would almost certainly rely on the operating system to perform the i/o.
If you want to replace the operating system with your own code, then you could well d... |
Willp = (users *)malloc(sizeof(users));create memory for the playlist structure too? Also how can I reference playlist.album using p?
```
struct playlist_ {
int album;
int track_num;
struct playlist_ *next;
};
struct users_ {
int user_ID;
struct playlist_ playlist;
struct users_ *next;
};
typedef struct... |
Willp = (users *)malloc(sizeof(users));create memory for the playlist structure too?
playlistis a member ofusers_, so it forms part of the allocated space. So to answer your question: yes.
[Incidentally, you don't need to (and shouldn't) cast the result ofmalloc.]
Also how can I reference playlist.album using p?
... |
GIven the fact that I generate a string containing "0" and "1" of a random length, how can I write the data to a file as bits instead of ascii text ?
Given my random string has 12 bits, I know that I should write 2 bytes (or add 4 more 0 bits to make 16 bits) in order to write the 1st byte and the 2nd byte.
Regardle... |
You don't do I/O with an array of bits.
Instead, you do two separate steps. First, convert your array of bits to a number. Then, do binary file I/O using that number.
For the first step, the typesuint8_tanduint16_tfound in<stdint.h>and the bit manipulation operators<<(shift left) and|(or) will be useful.
|
Is there a C function which can do the equivalent of find_first_not_of, receiving a string to search and a set of characters and returning the first character in the string that's not of the set?
|
Thestrspnfunction will get you most of the way there. (You just have to massage the return value a bit.)
|
```
...
int main(void)
{
int i;
for(i=0;i<2;i++){
switch(fork()){
case 0:
sleep(1);
break;
default:
sleep(1);
}
}
while(i--) wait(NULL);
return 0;
}
```
Hi. I'm trying to understand processes and forks.
I'm not sure how many processes doe... |
There is aforloop in the main thread (t1) that will callfork()twice (-> t1.1, t1.2). The first forked-thread (t1.1) has one more iteration, so it creates another (-> t1.1.1). Neither t1.2 nor t1.1.1 has any more iterations left, so no more threads forked.
This leaves us with 4 threads altoghether
|
I am trying to talk to my Arduino using a C program though a virtual com port (USB). The computer is running Windows and I am compiling the program using BloodShed. All I need is a basic communications library, but all I found so far is old libraries that could not compile on my machine.
Any suggestions on what I can... |
If you really are just trying to communicate with it over a USB to serial adapter then this may be of interest:http://web.archive.org/web/20120905123232/http://robbayer.com/files/serial-win.pdf
Looks like on windows you can just read and write to the COM port as if it were a file
As far as C++ IDEs go, QtCreator is ... |
With using plainCpreprocessor macros, is it possible to create something like:
```
INIT_BASE(0x100) // init starting number
#define BASE_A GET_NEXT_BASE // equivalent to #define BASE_A 0x101
#define BASE_B GET_NEXT_BASE // 0x102
#define BASE_C GET_NEXT_BASE // 0x103
```... |
Macros can't do that type of counting automatically, butenums can.
```
#define INIT_BASE 0x100
enum foo
{
BASE_A = INIT_BASE + 1,
BASE_B,
BASE_C,
...
};
```
Unless youreallywant to use macros, you are going to have to do the counting manually:
```
#define INIT_BASE 0x100
#define BASE_A (INIT_BAS... |
I'm starting to develop a client webservice in C/C++. I don't know which library to use. I've read about Axis2C and gSoap.
Any suggestion for developing a C/C++ SOAP webservice client? It seems that Axis2C is being discontinued.
|
Stay away from Axis2. Use gSOAP. If the web service is simple, you might also trywsdlpullas it's pretty lightweight.
|
I have a linux utility that parses structured input ( a text file ), processes it and prints the result to the screen. For example: (input)
```
COMMAND=create
NAME=Stack
SURNAME=Overflow
```
My utility takes as input the above text file and tries to create an object (stack, overflow) in the database. If the ... |
Google test is an awesome C++ framework, but it has a bit of a learning curve:https://github.com/google/googletest/
|
I want to write a simple program that determines whether the number the user inputs is increasing, strictly increasing, etc. etc.
To solve this I want to break up each digit and see if they are always getting smaller or not, etc.
How do I break up the input into separate digits using scanf function?
|
One has to wonder why you're not getting the input as integers in the first place (%lluperhaps?) - this would make comparisons so much easier. However, you could get each line from the user viafgetsand then parse each character.
Since you mention you want to read large numbers:
```
int64_t num;
scanf("%"PRId64, &num... |
I'm planning on writing a simple SSH client in C/C++ for a project in my intro networking class. I am having trouble, however, in finding good documentation on how to do this. I don't want extensive protocol specification, just a simple guide. Any suggestions?
|
I would take a look at thelibsslandlibcryptolibraries that are part of theOpenSSL project. On debian-based systems you can get the development libraries using:
```
sudo apt-get install libssl-dev
```
I would take a look at the files under/usr/share/doc/libssl-dev/demos
EDIT: Also, you canread the documentation here... |
```
Code
#include<stdio.h>
int main()
{
int i;
printf("%d \n",'\1');
printf("%d \n",'\022');
printf("%d ",'\555');
return 0;
}
```
Output:
1
18
109
When we compile this program then gcc compiler gives warning '\555' is octal escape sequence out of range? What is this range?
|
From the C99 spec, §6.4.4.4 Paragraph 9:
The value of an octal or hexadecimal escape sequence shall be in the
range of representable values for the type unsigned char for an
integer character constant, or the unsigned type corresponding to
wchar_t for a wide character constant.
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed8 years ago.Improve this question
Can you give me some ideas about how can I make a simple mathematical expression parser i... |
You can parse the expression based "Shunting-Yard Algorithm"http://en.wikipedia.org/wiki/Shunting-yard_algorithm. You will need to extend to handle the function calls such as sin, cos etc...
|
Is the only way of getting the address of an address in C (opposite to double dereference to have an intermediate variable?
e.g. I have:
```
int a;
int b;
int *ptr_a;
int *ptr_b;
int **ptr_ptr_a;
a = 1;
ptr_a = &a;
ptr_ptr_a = &(&a); <- compiler says no
ptr_ptr_a = &&a; <- still compiler says no
ptr__ptr_a = ... |
The address-of operator returns an rvalue, and you cannot take the address of an rvalue (seeherefor an explanation of the differences between rvalues and lvalues).
Therefore, you have to convert it into an lvalue by storing it in a variable, then you can take the address of that variable.
|
see i have refereedhttp://marakana.com/forums/android/examples/49.html
and make a java application using some sort of c code by jni now when ever i compile this package and get the .apk of that application.
But now my question is that here if have cross-compile c code for arm platform then this .apk will work on onl... |
According tohttp://source-android.frandroid.com/ndk/docs/APPLICATION-MK.html, you should put the lineAPP_ABI := allin yourApplication.mk, and than it will compile your code separately for each platform that support android.
(For only some platforms, you can write something likeAPP_ABI := armeabi x86)
|
Do you know a manner to access and manage in c interface eth0 without socket???
|
Why don't you do something along the lines of invoking theifconfigcommand on the shell within your C code:
```
system("ifconfig eth0 ...");
```
This will eliminate the need to have a file descriptor but allows you to manage the device using the command. Do aman ifconfigto see how to structure yourifconfigrequest to ... |
There is the POSIX library in c++ support wchar_t? if not, then how is it possible to solve this problem?
For example, I need openopendir(wchar_t*)
|
There's no POSIX wchar_t version of opendir. Your platform may have one if you are lucky. Otherwise, you'll have to use something like the iconv library to convert your wide character string into UTF-8 (or whatever character encoding your file system API uses).
|
In socket prgramming in "C" how do I find out the IP address of the Client who is connecting to the Server? How can the server get the client's IP address?
|
You didn't mention any API, but theacceptfunction/system call generally accepts asockaddr *argument where it stores the address of the peer.
```
int accept(int socket, struct sockaddr *restrict address, /* <---- */
socklen_t *restrict address_len);
```
Alternatively you can usegetpeernameto retrieve the same ... |
I want to pass message between two devices, for an example devices are PCs. Currently I am usingUDPServer.candUDPClient.cfor reference. By using this reference, I can pass messages, now I want to implement both side listen and send, also I want to create an API for sending message, that API can be used by other functi... |
From your description, it doesn't look like you need any more than whatsendto()/recvfrom()already do. You might as well treat them as your "API" for message passing. Once you set up/open the socket, just send/recv as needed. You don't need to worry about different ports for sending/receiving; your example is fine. FYI... |
I have a question which involves calling a function with 2 parameters of a pointer to a pointer
```
int main(void)
{ ...
int *ptrp = &p, *ptrq = &q;
int **ppp = &ptrp, **ppq = &ptrq;
swap_ptr(ppp,ppq);/* &ptrp, &ptrq passed */
/* to swap_ptr() */
return 0;
}
void swap_ptr(int **ptrA,int **ptrB)...
```
We have to ... |
It's the same concept as swapping anything:
```
void swap(int* a, int* b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
```
In this case, you just happen to be swapping int* instead of int:
```
void swap(int** a, int** b)
{
int* tmp = *a;
*a = *b;
*b = tmp;
}
```
|
I want to calculatelcm of 2 long long integersas fast as possible .
For ex
a=10^18
b=10^17
I was doinglcm(a,b)=a*b/gcd(a,b)for the integers
but forlong long there will be overflow
What should be thefastest wayto calculate it??
|
You're always going to have overflow problems, especially whenever you have large coprime numbers. But to offset this a little, you can do as Michael suggest by writinga * (b/gcd(a,b)). Sincegcd(a,b)is a divisor of bothaandb, there's no worry about inaccurate results due to integer division.
|
With using plainCpreprocessor macros, is it possible to create something like:
```
INIT_BASE(0x100) // init starting number
#define BASE_A GET_NEXT_BASE // equivalent to #define BASE_A 0x101
#define BASE_B GET_NEXT_BASE // 0x102
#define BASE_C GET_NEXT_BASE // 0x103
```... |
Macros can't do that type of counting automatically, butenums can.
```
#define INIT_BASE 0x100
enum foo
{
BASE_A = INIT_BASE + 1,
BASE_B,
BASE_C,
...
};
```
Unless youreallywant to use macros, you are going to have to do the counting manually:
```
#define INIT_BASE 0x100
#define BASE_A (INIT_BAS... |
I'm starting to develop a client webservice in C/C++. I don't know which library to use. I've read about Axis2C and gSoap.
Any suggestion for developing a C/C++ SOAP webservice client? It seems that Axis2C is being discontinued.
|
Stay away from Axis2. Use gSOAP. If the web service is simple, you might also trywsdlpullas it's pretty lightweight.
|
I have a linux utility that parses structured input ( a text file ), processes it and prints the result to the screen. For example: (input)
```
COMMAND=create
NAME=Stack
SURNAME=Overflow
```
My utility takes as input the above text file and tries to create an object (stack, overflow) in the database. If the ... |
Google test is an awesome C++ framework, but it has a bit of a learning curve:https://github.com/google/googletest/
|
I want to write a simple program that determines whether the number the user inputs is increasing, strictly increasing, etc. etc.
To solve this I want to break up each digit and see if they are always getting smaller or not, etc.
How do I break up the input into separate digits using scanf function?
|
One has to wonder why you're not getting the input as integers in the first place (%lluperhaps?) - this would make comparisons so much easier. However, you could get each line from the user viafgetsand then parse each character.
Since you mention you want to read large numbers:
```
int64_t num;
scanf("%"PRId64, &num... |
I'm planning on writing a simple SSH client in C/C++ for a project in my intro networking class. I am having trouble, however, in finding good documentation on how to do this. I don't want extensive protocol specification, just a simple guide. Any suggestions?
|
I would take a look at thelibsslandlibcryptolibraries that are part of theOpenSSL project. On debian-based systems you can get the development libraries using:
```
sudo apt-get install libssl-dev
```
I would take a look at the files under/usr/share/doc/libssl-dev/demos
EDIT: Also, you canread the documentation here... |
```
Code
#include<stdio.h>
int main()
{
int i;
printf("%d \n",'\1');
printf("%d \n",'\022');
printf("%d ",'\555');
return 0;
}
```
Output:
1
18
109
When we compile this program then gcc compiler gives warning '\555' is octal escape sequence out of range? What is this range?
|
From the C99 spec, §6.4.4.4 Paragraph 9:
The value of an octal or hexadecimal escape sequence shall be in the
range of representable values for the type unsigned char for an
integer character constant, or the unsigned type corresponding to
wchar_t for a wide character constant.
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed8 years ago.Improve this question
Can you give me some ideas about how can I make a simple mathematical expression parser i... |
You can parse the expression based "Shunting-Yard Algorithm"http://en.wikipedia.org/wiki/Shunting-yard_algorithm. You will need to extend to handle the function calls such as sin, cos etc...
|
Is the only way of getting the address of an address in C (opposite to double dereference to have an intermediate variable?
e.g. I have:
```
int a;
int b;
int *ptr_a;
int *ptr_b;
int **ptr_ptr_a;
a = 1;
ptr_a = &a;
ptr_ptr_a = &(&a); <- compiler says no
ptr_ptr_a = &&a; <- still compiler says no
ptr__ptr_a = ... |
The address-of operator returns an rvalue, and you cannot take the address of an rvalue (seeherefor an explanation of the differences between rvalues and lvalues).
Therefore, you have to convert it into an lvalue by storing it in a variable, then you can take the address of that variable.
|
see i have refereedhttp://marakana.com/forums/android/examples/49.html
and make a java application using some sort of c code by jni now when ever i compile this package and get the .apk of that application.
But now my question is that here if have cross-compile c code for arm platform then this .apk will work on onl... |
According tohttp://source-android.frandroid.com/ndk/docs/APPLICATION-MK.html, you should put the lineAPP_ABI := allin yourApplication.mk, and than it will compile your code separately for each platform that support android.
(For only some platforms, you can write something likeAPP_ABI := armeabi x86)
|
Do you know a manner to access and manage in c interface eth0 without socket???
|
Why don't you do something along the lines of invoking theifconfigcommand on the shell within your C code:
```
system("ifconfig eth0 ...");
```
This will eliminate the need to have a file descriptor but allows you to manage the device using the command. Do aman ifconfigto see how to structure yourifconfigrequest to ... |
There is the POSIX library in c++ support wchar_t? if not, then how is it possible to solve this problem?
For example, I need openopendir(wchar_t*)
|
There's no POSIX wchar_t version of opendir. Your platform may have one if you are lucky. Otherwise, you'll have to use something like the iconv library to convert your wide character string into UTF-8 (or whatever character encoding your file system API uses).
|
In socket prgramming in "C" how do I find out the IP address of the Client who is connecting to the Server? How can the server get the client's IP address?
|
You didn't mention any API, but theacceptfunction/system call generally accepts asockaddr *argument where it stores the address of the peer.
```
int accept(int socket, struct sockaddr *restrict address, /* <---- */
socklen_t *restrict address_len);
```
Alternatively you can usegetpeernameto retrieve the same ... |
I want to pass message between two devices, for an example devices are PCs. Currently I am usingUDPServer.candUDPClient.cfor reference. By using this reference, I can pass messages, now I want to implement both side listen and send, also I want to create an API for sending message, that API can be used by other functi... |
From your description, it doesn't look like you need any more than whatsendto()/recvfrom()already do. You might as well treat them as your "API" for message passing. Once you set up/open the socket, just send/recv as needed. You don't need to worry about different ports for sending/receiving; your example is fine. FYI... |
I have a question which involves calling a function with 2 parameters of a pointer to a pointer
```
int main(void)
{ ...
int *ptrp = &p, *ptrq = &q;
int **ppp = &ptrp, **ppq = &ptrq;
swap_ptr(ppp,ppq);/* &ptrp, &ptrq passed */
/* to swap_ptr() */
return 0;
}
void swap_ptr(int **ptrA,int **ptrB)...
```
We have to ... |
It's the same concept as swapping anything:
```
void swap(int* a, int* b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
```
In this case, you just happen to be swapping int* instead of int:
```
void swap(int** a, int** b)
{
int* tmp = *a;
*a = *b;
*b = tmp;
}
```
|
I want to calculatelcm of 2 long long integersas fast as possible .
For ex
a=10^18
b=10^17
I was doinglcm(a,b)=a*b/gcd(a,b)for the integers
but forlong long there will be overflow
What should be thefastest wayto calculate it??
|
You're always going to have overflow problems, especially whenever you have large coprime numbers. But to offset this a little, you can do as Michael suggest by writinga * (b/gcd(a,b)). Sincegcd(a,b)is a divisor of bothaandb, there's no worry about inaccurate results due to integer division.
|
```
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
uint32_t ip = 0;
printf("%s\n",inet_ntoa(*(struct in_addr *)ip));
return 0;
}
```
I don't want to do this by declaring any temporary variable. This program gives segmentation fault.
```
struct in_addr {
ui... |
You're casting an int to a pointer. Perhaps you want this:
```
*(struct in_addr *)&ip
```
But the result is implementation-defined (for a start, there're endianness considerations).
|
Is this correct, is it gonna leak memory in C?
```
unsigned char * prep( int length,int args, ... )
{
unsigned char *message = (unsigned char *) malloc(length );
va_list listp;
va_start( listp, args );
int i = 0;
int len = 0;
unsigned char *source_message ;
int step = 0;
for( i = 0 ... |
That's correct, it will leak memory. As long as you remember to free the return value of that function, you should be fine, however.
|
strtokfunction uses a static variable for parsing the string into tokens. So this causes a conflict when multiple calls are done. Other than using threads how could I do the following: thx- Can I use a function pointer to allocate the function at 2 different places? Would this make the static variable inside "strt... |
usestrtok_r()(re-entrant version).
|
```
char **s = &"Is this valid?";
```
Is obtaining the address at which the address of a string literal is stored allowed in C?
I know that the string literal is stored in the .rodata datasegment. However, obtaining the address of that address doesn't make sense.
It should be noted that gcc compiles this and produce... |
Your example is not valid:
```
char **s = &"Is this valid?"; // Not valid, wrong type
```
This is valid:
```
char (*s)[15] = &"Is this valid?"; // OK
```
The type of"Is this valid?"ischar[15]. The type of a pointer to an array 15 ofcharischar (*)[15]. So the type of&"Is this valid?"ischar (*)[15].
The type of ... |
Only constants can be used to declare the size of automatic and static
arrays. Not using a constant for this purpose is a compilation error.
Says Pearson.
However, following works fine. According to Pearson, it should not work (I think). Can you help me to understand this?
```
#include <iostream>
using namespace ... |
That's an extension to C++ that's found in the GNU compiler, but it doesn't conform to the C++ standard. If you compile your code usingg++ -std=c++98, the compiler should complain.
|
I am new to Cstring, sorry for asking dumb question, please help.
```
char string[10];
printf("Give me your last name:\n");
scanf ("%s", string); //if i type 123 123
printf("Original string:%s\n", string); //it shows 123
```
Compare to:
```
char string[] = "123 123";
printf("Original string:%s\... |
The problem is scanf. When you use scanf with %s it reads until it hits whitespace.
To read the entire line you may want to consider usingfgets().
|
For the following code snippets why would I use one assignment vs another? thx
```
void addOne(int &x)
{
x +=1;
}
void (*inc)(int &x) = addOne; // what is the purpose of doing "addOne"
void (*inc)(int &x) = &addOne; // vs &addOne ??
int a = 10;
inc(a);
```
|
The purpose of one over the other is C compatibility. C said that functions will decay to pointers-to-functions automatically. To be compatible, C++ had to do the same.
Note that when C++ introduced a new function pointer type (member function pointers), theydo notdecay automatically. So if the C++ committee had thei... |
How can I run an AppleScript from within an C commandline utility?
Googling didn't work, it only gave meObjective-C solutions...
EDIT:Oops, I should have googled for 'run shell script C'...Now i found thesystem()function...
|
I would use theexecfamily of functions, which is safer thansystem:
```
int exitCode = execlp("osascript", "osascript", "-e", "say \"Hello World\"", NULL);
```
|
While using theerrno, I once read words that
It is important to includeerrno.hrather than providing your ownextern int errno, sinceerrnois implemented in a thread-safe
manner that is more than just a simple globalint.
How does thethread-safemanner impact the difference between#includeandextern?
|
It's not the extern vs #include that matters
errno is defined in the header as
```
int* _errno(void);
#define errno (*_errno())
```
Each thread has it's own errno in it's own address space
|
Some C functions can modify the string value without that I pass the address of it.
For example:
```
char * s = "foo\0";
tobaa(s); /* Now foo is modified to something like "baa" */
printf("%s", s); /* baa */
```
How do I this?
|
Simple:
```
void tobaa(char *s)
{
strcpy(s, "baa");
}
```
Also, the extra\0character is unnecessary, it is added automatically.
Also, make sure you pass a mutable buffer totobaaor you invoke UB.
|
I'm trying to build a switch and I get an "expression must have integral or enum type". I'm guessing the switch in winapi doesn't take variables with LPSTR type?
```
char testbuf[ 51 ]; // allocate space for 50 characters + termination
LPSTR test = testbuf;
scanf("%50s", test); // read at most 50 characters
printf("%... |
This has nothing to do with WinAPI, it is plain C. The only thing you canswitchon are integral (int,charand similar) or enum types, like your compiler is telling your.
If you need to "switch" on strings, you'll need to build andif/elsesequence yourself and usestrcmpor a variant thereof.
|
I have code to dynamically allocate an array of 100 doubles to a pointer and initialize the memory with values from 1.0 to 100.0.
My question is, in the code below why don't I have to write *ptr++ at each iteration of the for loop. I've tried it and it doesn't work.
```
void allocate_array(){
double *ptr;
pt... |
Well, you don't have to do anything. In your code, you don't initialize the whole array - you just assign 100 different values to its first member. Your code is just like:
```
double d;
for(i=0;i<100;i++){
d=j++;
printf(" %0.1lf\n",d);
}
```
If you want to initialize the whole array, do somet... |
Is it possible to write a program in C that upon execution deletes itself (the binary) and then terminates successfully. If so, what's the easiest way of doing this?
|
Yes.
```
#include <unistd.h>
int main(int argc, char* argv[])
{
return unlink(argv[0]);
}
```
(Tested and works.)
Notethat ifargv[0]does not point to the binary (rewritten by caller) this will not work.
Similarly if run through a symlink then the symlink, not the binary, will be deleted.
Also if the file has mul... |
I am trying to get the name of a file when I select it using a file chooser.
I managed to do
```
gchar *name = gtk_file_chooser_get_filename(open_dialog);
```
but that will return/home/user/Desktop/test.fileand nottest.filewhich I want to.
Is there any method to get the name of the file and not the uri of it?
|
I would suggest using GIO (http://developer.gnome.org/gio/stable/). Its GFile and GFileInfo structures can be used for exactly what you need (also, GIO has the advantage to provide you with a portable file handling API).
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Pointer Arithmetic In C
Code:
```
int main()
{
int a[ ] ={0,1,2,3,4};
char c[ ] = {'s','a','n','j','u'};
printf("%d\n",&a[3]-&a[0]);
printf("%d\n",&c[3]-&c[0]);
return 0;
}
```
Why the output comes 3 3 for both... |
In pointer arithmetics, subtraction return the difference not in bytes, but in the pointer's type between two pointers.
So, since the difference inints betweena[3]anda[0]is identical to the difference inchars betweenc[3]andc[0]- you get the same result for both.
The arithmetics for pointers subtraction operation is ... |
I am trying to run make on a PintOS makefile but I keep getting the undefined reference to `floor' error. The makefile is below. I am running Ubuntu 11.10 with gcc 4.6.1. Any help is appreciated.
```
all: setitimer-helper squish-pty squish-unix
CC = gcc
CFLAGS = -Wall -W
LDFLAGS = -lm
setitimer-helper... |
-lmshould be inLDLIBS, notLDFLAGS.
The difference is important, because the implicit rule for linking executables is:
```
$(CC) $(LDFLAGS) n.o $(LOADLIBES) $(LDLIBS)
```
andld(invoked by GCC) has a strict left-to-right dependency-resolution algorithm.
|
As everybody knows, you have limited precision when you useprintfto output the value of afloat.However, there is a trick to increase the accuracy in the output, as this example shows:
```
#include <stdio.h>
int main()
{
float f = 1318926965; /* 10 random digits */
printf("%10.f\n", f); /* print... |
April fool?
Your "random number"1318926965have the same underlying representation both in decimal and floating-point form.
Try another value, like10. It will print as:
```
10
1092616192
```
So to answer your question:
```
and my question is, why don't people use this trick more often?
```
Because only one day of... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.