question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I have used the crypt function in c to encrypt the given string.
I have written the following code,
```
#include<stdio.h>
#include<unistd.h>
int main()
{
printf("%s\n",crypt("passwd",1000));
}
```
But the above code threw an error ,"undefined reference to `crypt'".
What is the problem in the above code.
Thanks in advance.
|
If you want to use thecrypt()function, you need to link to the library that supplies it. Add-lcryptto your compile command.
Older versions of glibc supplied alibcryptlibrary for this purpose, and declared the function in<unistd.h>- to compile against this support, you may also need to define either_XOPEN_SOURCEor_GNU_SOURCEin your code before including<unistd.h>.
Newer versions of glibc don't supplylibcrypt- it is instead provided by a separatelibxcrypt. You still link with-lcrypt, but the function is instead declared in<crypt.h>.
|
I want to make a Windows application in ansi C but I am having trouble with the graphic usage. Is ansi C able to handle the graphics of Windows without using any extra libraries? Guide line required.
|
ANSI (or more modernly ISO) C is thelanguage standard. It doesn't deal with graphics,at all.
However, you sure can write graphical applications with C (the language). On Windows you have the Win32 API, and there are also cross-platform libraries like GTK, which you can use to create graphical applications on Windows (as well as on other OSes).
|
I have a program which places structures in a linked list based on the 'name' they have stored in them.
To find their place in the list, i need to figure out if the name im inserting is earlier or later in the alphabet then those in the structures beside it.
The names are inside the structures, which i have access to.
I don't need a full comaparison if that is more work, even just the first letter is fine.
Thanks for the help!
|
It's not clear to me what your question is, but something like this would work:
```
if (node1->name[0] <= node2->name[0]) {
...
} else {
...
}
```
This will compare the first letter of the name in each of the nodes.
|
Given the following code:
```
int *a = NULL;
a = calloc(1, sizeof(*a));
printf("%d\n", a);
a = realloc(a, 0);
printf("%d\n", a);
return (0);
```
It returns:
```
4078904
0
```
Is this realloc equivalent to a free ?
NOTE:
I am using MinGW under WindowsXP.
|
It may or may not be equivalent to callingfreeon the pointer; the result is implementation-defined.
From the C99 standard (§7.20.3/1):
If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.
That applies to all of the memory management functions, includingrealloc.
|
When the VC6 C runtime on XP can't serve an allocation request within an existing heap segment, it reserves a new segment. The size of these new segments increase by factors of 2 (until there are not large enough free areas to do that, at which point it falls down to smaller segments.)
In any case, is there any way to control this behavior on XP with the VC6 runtime? For example, doubling up to a point, but capping at 64MB segments.
If there is no way on XP but there is on 7, that would be good to know too. Or if there is no way on VC6 but there is on VC8 or up would be interesting.
|
If you want specific allocation behaviour, write your own allocator. VirtualAlloc etc are there to help you do it. Using a compiler and CRT which is still in support would help too.
|
I want to use some basic struct in C like the following:
```
struct p {
int a;
int b;
p * next;
}
```
However, it fails to compile with anerror: parse error before "p"on the line withp * next;.
Do you have any idea what the reason could be for this problem?
|
C structs live in a different namespace and have to be explicitly scoped, thus:
```
struct p {
int a;
int b;
struct p * next;
};
```
And don't forget the semicolon at the end! :-)
You can pretend you're in C++ thus:typedef struct p { /*...*/ } p;. But I think thatnextwill still have be declared as above.
|
This question already has answers here:Easy way to use variables of enum types as string in C?(20 answers)Closed6 years ago.
gcc 4.4.2 c89
I have the following enum:
```
enum drop_options_e
{
drop_ssm,
drop_snm,
drop_ssb
};
```
I am just wondering that is the best way to get the string representation value from the enum.
So basically, instead of returning the value of 0 for drop_ssm, I could get the 'drop_ssm' instead.
Many thanks for any advice,
|
One way is to do like this:
```
enum drop_options_e
{
drop_ssm = 0,
drop_snm ,
drop_ssb ,
LAST_ENTRY /* Should be last entry */
};
const char* drop_options_s[LAST_ENTRY] = {"drop_ssm", "drop_snm", "drop_ssb"};
```
when you want a string representation of an enum you candrop_options_s[enum];
|
For example, how to get the version of /usr/lib/libz.a? It will be great if other useful information such as compiler/arch etc. can be fetched.
The reason I want to know this is that gcc always say it ignored the libz I offered in command line when I compile my program and linked with specific versioned libz. gcc think the /usr/lib/libz.a is a proper one.
|
C libraries do not have on their own a versioning system. At best, there is a symbol in the library that tells it.
|
I got some binary files containing integers. Is there some nice Unix command, that will allow me to dump it to a terminal without offset information, etc.?
Something like:
```
double int[4];
while (fread(tmp, sizeof(int), 4, stdin))
for(int i = 0; i < 4; i++)
printf("%d\t",tmp[i]);
```
It seems thathexdumpandodgives me the information I want, but the output is too verbose. I just want the contents.
|
To solve this kind of problem using standard Unix tools, you typically pipe a bunch together:
```
od -v -t d4 ~/.profile | awk '{$1 = ""; print}' | fmt -1 | sed 's/^ *//'
```
Theodprints every 32-bit word in decimal, with preceding offsets. Theawkcomment removes the offsets. Thefmtcommand forces one integer per line. Thesedcommand strips leading spaces off the result.
|
I was wondering how you could detect what platform a program is running on, I have an application and need it to go to a certain folder depending on whether it is on a Linux or Mac machine.
Thanks!
|
It may break in the future, but for now, you can play on a large number of filesystem differences between both.
/Applications, /Developer, /Library and others are mac-specific. If you have them, it looks like a mac./proc, /home, /srv and others are linux-specific. If they are there, it looks like a linux machine. Seefull list.
If you combine several of these path-checking tricks into a function, you can insulate yourself against any one of the tricks failing independently of the others.
You can check for folder existence by using stat.
```
struct stat st;
if(stat("/proc",&st) == 0) {
printf(" /proc is present: this may be Linux\n");
}
```
|
I have a static C library (saymylib.a) and I was wondering if it's possible to find out what functions are implemented inside that file. I don't have a corresponding header file. what I need is like the equivalent ofjavapfor Java.
|
On Windows you can usedumpbin. On Linux and friends you can usenm.
|
example some array {2,8,9,10,21,32,1,6,3...}
first child take (data size / 2) and sort
second chile take (data size / 2) and sort after combine 2 child data and give us a sorted full data, is it possible with some algorithms?
|
Yes, there are actually many parallel sorting algorithms existing.
Some interesting links with many different parallel sorting algorithms :
A Library of Parallel AlgorithmsComputer Programming Algorithms DirectorySequential and parallel sorting algorithms
Some implementations :
Parallel quicksort implementation using MPI and PThreadsParallel Sorting Strategies
But I advice you to search google withparallel sorting algorithmsfor more information.
|
Using C on Linux, how would I go about triggering a signal handler every time I write data to a buffer using the write() function. The handler will be reading all data written to the buffer at the time of execution.
|
Sockets support this by enabling async mode on the socket file descriptor. On Linux this is done using fcntl calls:
```
/* set socket owner (the process that will receive signals) */
fcntl(fd, F_SETOWN, getpid());
/* optional if you want to receive a real-time signal instead of SIGIO */
fnctl(fd, F_SETSIG, signum);
/* turn on async mode -- this is the important part which enables signal delivery */
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_ASYNC);
```
|
I am trying to move some code from a separate binary and have it inside my main program. Unfortunately I can't mimic the initialization variables for the main function.
How can I createargcandargvby hand? Can someone give me some example assignments.
since it looks like this:
```
int main(int argc, char *argv[])
```
I figured I could assign them like this:
```
int argc=1;
char *argv[0]="Example";
```
But it doesn't work. Can anyone tell me how this might be done?
|
```
int argc = 3;
char *argv[4];
argv[0] = "fake /path/to/my/program";
argv[1] = "fake arg 1";
argv[2] = "fake arg 2";
argv[3] = NULL;
fakemain(argc, argv);
```
|
I have written an app in C which expects two lines at input.
First input tells how big an array of int will be and the second input contains values separated by space.
For example, the following input
```
5
1 2 3 4 99
```
should create an array containing{1,2,3,4,99}
What is the fastest way to do so? My problem is to read multiple numbers without looping through the whole string checking if it's space or a number?
Thanks.
|
```
int i, size;
int *v;
scanf("%d", &size);
v = malloc(size * sizeof(int));
for(i=0; i < size; i++)
scanf("%d", &v[i]);
```
Remember tofree(v)after you are done!
Also, if for some reason you already have the numbers in a string, you can usesscanf()
|
I am new to C programming and I'd like to implement chmod command on files of a dir and subdir. How can I change/show permissions with a C code? Could someone help with a example? I would appreciate if anyone can provide me a code.
|
There's a chmod function. Fromman 3p chmod:
```
SYNOPSIS
#include <sys/stat.h>
int chmod(const char *path, mode_t mode);
...
```
If you want to read the permissions, you'd use stat. Fromman 3p stat:
```
SYNOPSIS
#include <sys/stat.h>
int stat(const char *restrict path, struct stat *restrict buf);
...
```
If you want to do it recursively like you mentioned, you'll have to do the looping over results ofreaddiryourself.
|
I just started readingHacker's Delightand it defines abs(-231) as -231. Why is that?
I triedprintf("%x", abs(0x80000000))on a few different systems and I get back 0x80000000 on all of them.
|
Actually, in C, the behavior is undefined. From the C99 standard, §7.20.6.1/2:
Theabs,labs, andllabsfunctions compute the absolute value of an integerj. If the result cannot be represented, the behavior is undefined.
and its footnote:
The absolute value of the most negative number cannot be represented in two’s complement.
|
Is it possible to capture full screen in visual studio (VC++), so that user don't have to press ATL+Enter. Kindly guide me how I can make it possible.
|
If you need to enter fullscreen mode in OpenGL per default, check out NeHe Productions, for instance hissecond lessonIf you download his example at the bottom of the screen and check out the:BOOL CreateGLWindow(char* title, int width, int height, int bits, boolfullscreenflag).. you will see how it can be made in OpenGL
|
I need some help deciding what to use to acquire an image from a webcam. I want to acquire a single image. I know you can typically acquire a still image at a higher resolution than a single video frame.
Currently, I am using MATLAB's image acquisition toolbox.. which apparently only supports obtaining frames in video mode(so lower resolution). Which other libraries do you recommend? Has anyone else encountered this problem?
|
Are you referring to the fact that the largest resolution reported by the Image Acquisition Toolbox is (for example) 1024x768 but the webcam claims that it can acquire 6 megapixel still images? If so, every webcam that I have ever seen has a note in very small print somewhere that explains that the higher resolution is achieved via software interpolation.
You can just acquire the image in the largest format supported by the toolbox and then useIMRESIZEto scale the image to whatever resolution that you want.
|
if this is a bad idea, how to allocate memory in the function?
|
It's not a "bad idea", but rather "sometimes a bad idea", which can be said about many ideas in programming.
Allocating memory inside a function and releasing it outside may be a common design pattern, by the way. Consider:
```
// hashtable is a typedef-ed pointer type
hashtable ht = hashtable_new();
// .. do something with hashtable
hashtable_free(ht);
```
htwas allocated in a functionhashtable_newand released outside it, yet you will see this pattern over and over in lots of good C code.
What it does show, however, is how the samelogical unit(the hash-table ADT) takes care of allocation and de-allocation. This makes lots of sense - because the one who knows how to allocate, knows best how to deallocate. Allocating and releasing in differentlogical unitsis more often a bad idea.
|
Given a simple data set, I would like to be able to calculate atrendingformula given it's a second order polynomial regression.
In fact, it would be great if one could even forecast X periods during calculation (similar to what Excel does).
I'm looking for a portable C/C++ package that's relatively easy to use, and allows it to spit out the "best-fit" (highest R^2 value) curve.
Any suggestions? Thanks!
|
The GNUgslClibrary can do multiparameter fits. Its interface is of course veryC-like, but there are version for many platforms available, including for Windows.
See thequadratic fit examplein thegsldocumentation for how to implement this for your case.
|
after calling JetSetColumns() and then JetUpdate() how do I retrieve the values for any freshly assigned autoincrement values?
|
when you call JetUpdate() the third arg is a 'bookmark'. Once JetUpdate() completes you can seek to the bookmark using
JetGotoBookmark() -http://msdn.microsoft.com/en-us/library/ms683554(EXCHG.10).aspx
|
I want to compile a simple hello-world-style program using the Windows command line.
```
cl file_name.c
```
is easy enough. Now I want to do the same thing in 64 Bit. What should I do?
|
You need to use a version of the cl.exe compiler which emits x64 code. Which one depends a bit on your setup.
Let's consider the case you're on a 64 bit machine. For this you'll need to use the compiler which lives at
c:\Program Files (x86)\Microsoft visual Studio 10.0\VC\bin\amd64\cl.exe
If you're on a 32 bit machine you'll need to use the cross compiler located at
c:\Program Files\Microsoft Visual Studio 10.0\VC\bin\x86_amd64\cl.exe
|
Is size_t only in C++ standard or C standard as well?
I cannot find a C header in the "/usr/include" tree that defines size_t.
If it is not in the C std, is GCC just doing some magic to make things work?
Thanks,
Chenz
|
size_tis defined in both<stddef.h>and<stdlib.h>
|
Given the following code:
```
int *a = NULL;
a = calloc(1, sizeof(*a));
printf("%d\n", a);
a = realloc(a, 0);
printf("%d\n", a);
return (0);
```
It returns:
```
4078904
0
```
Is this realloc equivalent to a free ?
NOTE:
I am using MinGW under WindowsXP.
|
It may or may not be equivalent to callingfreeon the pointer; the result is implementation-defined.
From the C99 standard (§7.20.3/1):
If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.
That applies to all of the memory management functions, includingrealloc.
|
When the VC6 C runtime on XP can't serve an allocation request within an existing heap segment, it reserves a new segment. The size of these new segments increase by factors of 2 (until there are not large enough free areas to do that, at which point it falls down to smaller segments.)
In any case, is there any way to control this behavior on XP with the VC6 runtime? For example, doubling up to a point, but capping at 64MB segments.
If there is no way on XP but there is on 7, that would be good to know too. Or if there is no way on VC6 but there is on VC8 or up would be interesting.
|
If you want specific allocation behaviour, write your own allocator. VirtualAlloc etc are there to help you do it. Using a compiler and CRT which is still in support would help too.
|
I want to use some basic struct in C like the following:
```
struct p {
int a;
int b;
p * next;
}
```
However, it fails to compile with anerror: parse error before "p"on the line withp * next;.
Do you have any idea what the reason could be for this problem?
|
C structs live in a different namespace and have to be explicitly scoped, thus:
```
struct p {
int a;
int b;
struct p * next;
};
```
And don't forget the semicolon at the end! :-)
You can pretend you're in C++ thus:typedef struct p { /*...*/ } p;. But I think thatnextwill still have be declared as above.
|
This question already has answers here:Easy way to use variables of enum types as string in C?(20 answers)Closed6 years ago.
gcc 4.4.2 c89
I have the following enum:
```
enum drop_options_e
{
drop_ssm,
drop_snm,
drop_ssb
};
```
I am just wondering that is the best way to get the string representation value from the enum.
So basically, instead of returning the value of 0 for drop_ssm, I could get the 'drop_ssm' instead.
Many thanks for any advice,
|
One way is to do like this:
```
enum drop_options_e
{
drop_ssm = 0,
drop_snm ,
drop_ssb ,
LAST_ENTRY /* Should be last entry */
};
const char* drop_options_s[LAST_ENTRY] = {"drop_ssm", "drop_snm", "drop_ssb"};
```
when you want a string representation of an enum you candrop_options_s[enum];
|
For example, how to get the version of /usr/lib/libz.a? It will be great if other useful information such as compiler/arch etc. can be fetched.
The reason I want to know this is that gcc always say it ignored the libz I offered in command line when I compile my program and linked with specific versioned libz. gcc think the /usr/lib/libz.a is a proper one.
|
C libraries do not have on their own a versioning system. At best, there is a symbol in the library that tells it.
|
I got some binary files containing integers. Is there some nice Unix command, that will allow me to dump it to a terminal without offset information, etc.?
Something like:
```
double int[4];
while (fread(tmp, sizeof(int), 4, stdin))
for(int i = 0; i < 4; i++)
printf("%d\t",tmp[i]);
```
It seems thathexdumpandodgives me the information I want, but the output is too verbose. I just want the contents.
|
To solve this kind of problem using standard Unix tools, you typically pipe a bunch together:
```
od -v -t d4 ~/.profile | awk '{$1 = ""; print}' | fmt -1 | sed 's/^ *//'
```
Theodprints every 32-bit word in decimal, with preceding offsets. Theawkcomment removes the offsets. Thefmtcommand forces one integer per line. Thesedcommand strips leading spaces off the result.
|
I was wondering how you could detect what platform a program is running on, I have an application and need it to go to a certain folder depending on whether it is on a Linux or Mac machine.
Thanks!
|
It may break in the future, but for now, you can play on a large number of filesystem differences between both.
/Applications, /Developer, /Library and others are mac-specific. If you have them, it looks like a mac./proc, /home, /srv and others are linux-specific. If they are there, it looks like a linux machine. Seefull list.
If you combine several of these path-checking tricks into a function, you can insulate yourself against any one of the tricks failing independently of the others.
You can check for folder existence by using stat.
```
struct stat st;
if(stat("/proc",&st) == 0) {
printf(" /proc is present: this may be Linux\n");
}
```
|
I have a static C library (saymylib.a) and I was wondering if it's possible to find out what functions are implemented inside that file. I don't have a corresponding header file. what I need is like the equivalent ofjavapfor Java.
|
On Windows you can usedumpbin. On Linux and friends you can usenm.
|
example some array {2,8,9,10,21,32,1,6,3...}
first child take (data size / 2) and sort
second chile take (data size / 2) and sort after combine 2 child data and give us a sorted full data, is it possible with some algorithms?
|
Yes, there are actually many parallel sorting algorithms existing.
Some interesting links with many different parallel sorting algorithms :
A Library of Parallel AlgorithmsComputer Programming Algorithms DirectorySequential and parallel sorting algorithms
Some implementations :
Parallel quicksort implementation using MPI and PThreadsParallel Sorting Strategies
But I advice you to search google withparallel sorting algorithmsfor more information.
|
Using C on Linux, how would I go about triggering a signal handler every time I write data to a buffer using the write() function. The handler will be reading all data written to the buffer at the time of execution.
|
Sockets support this by enabling async mode on the socket file descriptor. On Linux this is done using fcntl calls:
```
/* set socket owner (the process that will receive signals) */
fcntl(fd, F_SETOWN, getpid());
/* optional if you want to receive a real-time signal instead of SIGIO */
fnctl(fd, F_SETSIG, signum);
/* turn on async mode -- this is the important part which enables signal delivery */
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_ASYNC);
```
|
I am trying to move some code from a separate binary and have it inside my main program. Unfortunately I can't mimic the initialization variables for the main function.
How can I createargcandargvby hand? Can someone give me some example assignments.
since it looks like this:
```
int main(int argc, char *argv[])
```
I figured I could assign them like this:
```
int argc=1;
char *argv[0]="Example";
```
But it doesn't work. Can anyone tell me how this might be done?
|
```
int argc = 3;
char *argv[4];
argv[0] = "fake /path/to/my/program";
argv[1] = "fake arg 1";
argv[2] = "fake arg 2";
argv[3] = NULL;
fakemain(argc, argv);
```
|
I have written an app in C which expects two lines at input.
First input tells how big an array of int will be and the second input contains values separated by space.
For example, the following input
```
5
1 2 3 4 99
```
should create an array containing{1,2,3,4,99}
What is the fastest way to do so? My problem is to read multiple numbers without looping through the whole string checking if it's space or a number?
Thanks.
|
```
int i, size;
int *v;
scanf("%d", &size);
v = malloc(size * sizeof(int));
for(i=0; i < size; i++)
scanf("%d", &v[i]);
```
Remember tofree(v)after you are done!
Also, if for some reason you already have the numbers in a string, you can usesscanf()
|
I am new to C programming and I'd like to implement chmod command on files of a dir and subdir. How can I change/show permissions with a C code? Could someone help with a example? I would appreciate if anyone can provide me a code.
|
There's a chmod function. Fromman 3p chmod:
```
SYNOPSIS
#include <sys/stat.h>
int chmod(const char *path, mode_t mode);
...
```
If you want to read the permissions, you'd use stat. Fromman 3p stat:
```
SYNOPSIS
#include <sys/stat.h>
int stat(const char *restrict path, struct stat *restrict buf);
...
```
If you want to do it recursively like you mentioned, you'll have to do the looping over results ofreaddiryourself.
|
I just started readingHacker's Delightand it defines abs(-231) as -231. Why is that?
I triedprintf("%x", abs(0x80000000))on a few different systems and I get back 0x80000000 on all of them.
|
Actually, in C, the behavior is undefined. From the C99 standard, §7.20.6.1/2:
Theabs,labs, andllabsfunctions compute the absolute value of an integerj. If the result cannot be represented, the behavior is undefined.
and its footnote:
The absolute value of the most negative number cannot be represented in two’s complement.
|
```
char a[]="HELLO";
char *p="HELLO";
```
willa[2]andp[2]fetch the same character?
|
What they will fetch is a char-sized chunk of memory located 2 char-sized steps (2 bytes here) after the beginning of each, or after the address in memory to which each var points. This happens to be 'L' i the example, but this is not the same address in memory.
So yes, in the example given, they will fetch the same character.
|
I have a question relating to alignment in C/C++. InDetermining the alignment of C/C++ structures in relation to its membersMichael Burr posted this macro:
```
#define TYPE_ALIGNMENT( t ) offsetof( struct { char x; t test; }, test )
```
In the comments someone wrote this might fail with non POD types. Can someone give me an code example where this fails?
|
offsetofis only specified to work for POD types. If a class contains any data members that are not POD, the class itself is not POD. So, iftin your example is a non-POD type, it is not guaranteed to work.
From the C++ standard (18.1/5):
The macrooffsetofaccepts a restricted set oftypearguments in this International Standard.typeshall be a POD structure or a POD union.
So, if you useoffsetofon a non-POD type, the results are undefined.
|
If you write a ruby method as a function in C that usesrb_raise, the part of the function after the call will not get excecuted and the program will stop and you will think thatrb_raiseusedexit(). But if you rescue the exception in ruby, like:
```
begin
method_that_raises_an_exception
rescue
end
puts 'You wil still get here.'
```
The ruby code will go on, but your function will stop excecuting. How doesrb_raisemake this happen?
|
Presumably it usessetjmp(before the method is called) andlongjmp(inrb_raise).
|
How can I use zlib library to decompress a PNG file? I need to read a PNG file using a C under gcc compiler.
|
Why not uselibpng? The PNG file format is fairly simple, but there are many different possible variations and encoding methods and it can be fairly tedious to ensure you cover all of the cases. Something like libpng handles all the conversion and stuff for you automatically.
|
How to Join N live MP3 streams (radio streams like such live KCDX mp3 streamhttp://mp3.kcdx.com:8000/stream) into 1 using FFMPEG? (I have N incoming live mp3 streams I want to join them and stream out 1 live mp3 stream) I mean I want to mix sounds like thay N speakers speak at the same time (btw N stereo to 1 mono), please help.
BTW: My problem is mainly how to make FFMPEG read from stream not from file...
Would you mind giving some code examples, please.
|
It looks likeurl_fopen(), defined in avio.h, is the function you are looking for.
|
I am interested in porting a C library that depends on glib to Symbian.
After some research, I found that there is a Symbian port of glib. However I can't seem to find much documentation about it. Can anyone point me to the right direction as to whether this can be even done or not? If yes, how.
|
Forum Nokiahas a lot of resources for developing for Nokia/S60 devices.
The glib port is part of theOpen C/C++ plug-ins. Download and install them on top of your SDK to get started.
|
I want to write data into the file in binary form.
I was trying using the mentioned below
```
FILE *fp = fopen("binaryoutput.rgb888", "ab+");
for(int m=0; m<height; m++)
{
for (int n=0; n< width; n++)
{
temp = (pOutputImg+m*3+n*3); // here pOutputImg & temp is a pointer to a unsigned char
fprintf(fp,"%u",*temp);
}
}
fclose(fp);
```
I am able to get data which is strored at pOutputImg but not in binary form.
Can anyone guide me the correct step..
Thanks in advance
|
Replace fprintf() with fwrite().
Ex:
```
fwrite(temp, sizeof(*temp), 1, fp);
```
The whole purpose of fprintf() is to format binary data as readable ascii ... the exact opposite of what you want. fwrite() is for directly writing binary data.
|
My question is:If a pointer variable has the same address as its value, is it really pointing to itself?
For example - in the following piece of code, isaa pointer to itself?
```
#include<stdio.h>
int main(){
int* a;
int b = (int)&a;
a = b;
printf("address of a = %d\n", &a);
printf(" value of a = %d\n", a);
}
```
Ifais not a pointer to itself, then the same question poses again:Can a pointer point to itself?Also, how is a self pointing pointer useful?
|
```
void* p = &p;
```
It's not terribly useful, but structs that point to themselves are useful in circular lists of length 1:
```
typedef struct A {
struct A* next;
} A;
A a = { &a };
```
Per your exact example, I believe you meant:
```
int* a;
int b = (int)&a;
a = (int*)b;
// which can be simplified to:
int* a = (int*)&a;
```
|
Supposing I have this:
```
"foo bar 1 and foo bar 2"
```
How can I split it into:
```
foo bar 1
foo bar 2
```
?
I triedstrtok()andstrsep()but neither worked. They don't recognize "and" as delimiter, they recognize "a", "n" and "d" as delimiters.
Any function to help me with this or I'll have to split by the blank space and do some string manipulation?
|
You can usestrstr()to find the first " and ", and "tokenize" the string yourself by just skipping forward so many characters, and doing it again.
|
I am using the Eclipse CDT and I have agotolabel and a FILE definition after it and when I compile the project it gives me the error:Expression expected before FILE.
Thanks in advance,
Mr. Man
EDIT:
Ok, so this is what I get from the command line:
```
iOS.c: In function ‘main’:
iOS.c:45: error: expected expression before ‘FILE’
iOS.c:49: error: ‘preFile’ undeclared (first use in this function)
iOS.c:49: error: (Each undeclared identifier is reported only once
iOS.c:49: error: for each function it appears in.)`
```
And this is what code throws the error:
```
fileExists:
FILE *preFile = fopen("prefix.txt","r");
```
|
As you're coding in C, you need to declare the variable at the beginning of the function:
```
void foo()
{
FILE* preFile;
// some code
fileExists:
preFile = fopen("prefix.txt","r");
}
```
|
when i read through source files of opensource projects i often come across some weird phrases in the comments
```
/*
@brief ......
@usage.....
@remarks....
@par....
*/
```
questions1.What are they?(were not mentioned when i was learning c++)2.Do they have any documentation(where)
|
They are just comments and as such have no special meaning in C++. They are probably to allow a documentation generator (For exampleDoxygen) to extract the data from the comments.
|
Is it even possible to create an array of bits with more than 100000000 elements? If it is, how would I go about doing this? I know that for a char array I can do this:
char* array;
array = (char*)malloc(100000000 * sizeof(char));
If I was to declare the array bychar array[100000000]then I would get a segmentation fault, since the maximum number of elements has been exceeded, which is why I usemalloc.
Is there something similar I can do for an array of bits?
|
If you are using C++,std::vector<bool>is specialized to pack elements into a bit map. Of course, if you are using C++, you need to stop usingmalloc.
|
I read file, but in the end of file i get unknown symbols:
```
int main()
{
char *buffer, ch;
int i = 0, size;
FILE *fp = fopen("file.txt", "r");
if(!fp){
printf("File not found!\n");
exit(1);
}
fseek(fp, 0, SEEK_END);
size = ftell(fp);
printf("%d\n", size);
fseek(fp, 0, SEEK_SET);
buffer = malloc(size * sizeof(*buffer));
while(((ch = fgetc(fp)) != NULL) && (i <= size)){
buffer[i++] = ch;
}
printf(buffer);
fclose(fp);
free(buffer);
getch();
return 0;
}
```
|
You need to add anullchar at the end of buffer before you print:
```
while(((ch = fgetc(fp)) != NULL) && (i <= size)){
buffer[i++] = ch;
}
buffer[i] = 0; // add a null char at the end.
printf("%s",buffer); // print using %s format specifier.
```
|
In my C OpenGL app the window style requires WS_SYSMENU to show the close and minimize buttons, but it also brings up a stupid menu everytime I press alt.
How can I disable this?
|
One way is to handle WM_DEADCHAR and WM_SYSCHAR and discard the press of the ALT key (or do your own processing). This will still allow the user to activate the menu with the mouse and from the taskbar... which is why you really shouldn't disable it completely, users like to be able to manipulate windows from the taskbar.
|
strtok wont work correctly when using char *str as the first parameter (not the delimiters string).
Does it have something to do with the area that allocates strings in that notation? (which as far as i know, is a read-only area).
thanks in advance
example:
```
//char* str ="- This, a sample string."; // <---doesn't work
char str[] ="- This, a sample string."; // <---works
char delims[] = " ";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str,delims);
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, delims);
}
return 0;
```
|
In the first case, you pass a string literal to strtok(). As strtok() modifies this string, and as string literals cannot legally be modified, you end up with undefined behaviour. In the second case, the compiler copies the string into the array. Array contents can be modified, so this code is OK.
|
here is my coding which gives me the error 'warning: unknown conversion type character 0x20 in format'
```
int subtotal;
long long a,b,c,d,e,f,g,h,i,j,k,l,m;
subtotal = (1*(a+c+e+g+i+k))+(3*(b+d+f+h+j+l));
printf(" = %d % 10 = %d; (10 - %d) % 10 = %lld\n", subtotal,subtotal%10,subtotal%10,m);
```
any idea why this is wrong?
|
Ignoring the fact you have a bunch of uninitialised variables, the % character is a special one in printf format strings - if you want a literal '%', you need '%%'.
```
printf(" = %d %% 10 = %d; (10 - %d) %% 10 = %lld\n", subtotal,subtotal%10,subtotal%10,m);
```
|
I am trying to use my own function to get the file size from a file. I'll use this to allocate memory for a data structure to hold the information on the file.
The file size function looks like this:
```
long fileSize(FILE *fp){
long start;
fflush(fp);
rewind(fp);
start = ftell(fp);
return (fseek(fp, 0L, SEEK_END) - start);
}
```
Any ideas what I'm doing wrong here?
|
Do
```
fseek(fp, 0L, SEEK_END);
return (ftell(fp) - start);
```
instead of
```
return (fseek(fp, 0L, SEEK_END) - start);
```
becausefseekreturn zero on success not the offset as you are expecting here.
|
when I'm trying to compile my c program it gives me this error warning: integer constant is too large for 'long' type
which refers to these lines
```
int barcode, a, b, c;
scanf("%d", &barcode);
a = barcode / 1000000000000;
b = barcode / 100000000000 % 10;
c = barcode / 10000000000 % 10;
```
and the rest is fine. I know I'm not supposed to use int for such a large number, any suggestions on what I should use? if I replace int with double what should the '%d' part be replaced with then?
|
Use long longs instead of ints for integer values of that size, with the LL literal suffix:
```
long long barcode, a, b, c;
scanf("%lld", &barcode);
a = barcode / 1000000000000LL;
b = barcode / 100000000000LL % 10;
c = barcode / 10000000000LL % 10;
```
|
Is there any difference between a variable declared asstaticoutside any function between C and C++. I read thatstaticmeans file scope and the variables will not be accessible outside the file. I also read that in C, global variables arestatic. So does that mean that global variables in C can not be accessed in another file?
|
No, there's no difference between C and C++ in this respect.
Readthis SO answerabout whatstaticmeans in a C program. In C++ there are a couple of other meanings related to the use ofstaticfor class variables (instead of instance variables).
Regarding global vars beingstatic- only from the point of view of memory allocation (they are allocated on the data segment, as all globals are). From the point of view of visibility:
```
static int var; // can't be seen from outside files
int var; // can be seen from outside files (no 'static')
```
|
What is the best way to accomplish the following in C?
```
#include <stdio.h>
struct A
{
int x;
};
struct A createA(int x)
{
struct A a;
a.x = x;
return a;
}
struct A a = createA(42);
int main(int argc, char** argv)
{
printf("%d\n", a.x);
return 0;
}
```
When I try to compile the above code, the compiler reports the following error:
"initializer element is not constant"
The bad line is this one:
```
struct A a = createA(42);
```
Can someone explain what is wrong? I'm not very experienced in C. Thanks!
|
```
struct A a = { .x = 42 };
```
More members:
```
struct Y {
int r;
int s;
int t;
};
struct Y y = { .r = 1, .s = 2, .t = 3 };
```
You could also do
```
struct Y y = { 1, 2, 3 };
```
The same thing works for unions, and you don't have to include all of the members or even put them in the correct order.
|
I'm doing a steganography project where I read in bytes from a ppm file and add the least significant bit to an array. So once 8 bytes are read in, I would have 8 bits in my array, which should equal some character in a hidden message. Is there an easy way to convert an array of 0's and 1's into an ascii value? For example, the array:char bits[] = {0,1,1,1,0,1,0,0}would equal 't'.Plain C
Thanks for all the answers. I'm gonna give some of these a shot.
|
A simpleforloop would work - something like
```
unsigned char ascii = 0;
unsigned char i;
for(i = 0; i < 8; i++)
ascii |= (bits[7 - i] << i);
```
There might be a faster way to do this, but this is a start at least.
|
in the Winsock2 librarygetaddrinfo()andfreeaddrinfo()was only added in Windows XP and on. I know how to replace them in legacy systems, but a conditional use depending on the Windows version won't help.
The application won't start in 9x with a message saying that it was linked to a missing export in WS2_32.dll.
I'm using MinGW to compile and link the code and would like to keep using it. Maybe writing those functions by myself?
Thank you very much for everything.
|
You can useLoadLibraryandGetProcAddressto (attempt to) get the addresses ofgetaddrinfoandfreeaddrinfo, then call them via the pointers iffGetProcAddressreturns a non-NULL pointer.
|
// File: foo.c
```
static int var;
void foo()
{
var++;
}
```
// end of file foo.c
// File bar.c:
```
static int var;
void bar()
{
var++;
}
```
// end of file bar.c
// file main.c
```
static int var;
void main()
{
foo();
bar();
printf("%d", var);
}
```
// end of file main.c
Question: Will the above program compile ? If so what will be the result ?
I tested the code and found it couldn't be compiled. I try to use extern in main.c to use the function foo() and bar() but it still couldn't be compiled.
|
main.c has a few minor problems - it should be something like this:
```
#include <stdio.h>
static int var;
extern void foo();
extern void bar();
int main(void)
{
foo();
bar();
printf("%d\n", var);
return 0;
}
```
It should build OK like this:
```
$ gcc -Wall main.c foo.c bar.c -o main
```
and the result should be:
```
$ ./main
0
```
|
Is there a way I can have a pad refresh to any window instead of (presumably)stdscr? I suppose I could temporarily changestdscrevery time I want to draw the pad, but that seems a little silly.
|
I just happened to have exactly same need for such function and I was more lucky: Trycopywinfunction, it should do what you need. However - unlikeprefresh- it doesn't do the refresh - you have to refresh the destination window yourself to display copied data.
http://nfosolutions.com/doc_link/C/a_doc_lib/libs/basetrf2/copywin.htm
|
I am looking at approaches to Unit Test embedded systems code written in C.
At the same time, I am also looking for a good UT framework that I can use. The framework should have a reasonably small number of dependencies.
Any great Open-source products that have good UTs?
EDIT:
Folks, thanks for the answers --Ireallyappreciate them, but this does notdirectlyanswer my question:
Do you know of any Open-source code that uses C Unit Tests? I am looking to see how it's done, so that I can learn something from the code...
|
Modularize your code in such a way that there is a thin layer in the bottom which knows about the details of the underlying hardware. That layer can then be mocked on a normal PC. That way you can use normal unit test libraries for desktop development to test all code except that thin bottom layer.
My experience on developing embedded software for Linux is using C++ and not plain C. We used cppunit for unit tests.
|
How to make a block of memory allocated by malloc() or new:
immediately swapped out,or lazily initialized.
In fact, I'm trying to reserve an address space. How to accomplish this?
PS. How to verify, from the user space, if a memory block is swapped out?
|
malloc is often implemented using mmap, so if you were to use malloc, you'd get the behavior you're after anyway. After all, why sould allocating memory force other pages out of cache when there's no guarantee that the new pages will be initialized immediately? I know that Open BSD implements malloc this way, and GNU's C lib uses mmap if your allocation is larger than some limit. I think it's just a couple pages.
I don't know about how Windows goes about all of this, but check the VirtualAlloc docs to see if it is specific about its purpose. If it documents that Windows' malloc caches its pages, then you have your answer and you should use VirtualAlloc.
|
I want to repeatedly zero a large 2d array in C. This is what I do at the moment:
```
// Array of size n * m, where n may not equal m
for(j = 0; j < n; j++)
{
for(i = 0; i < m; i++)
{
array[i][j] = 0;
}
}
```
I've tried using memset:
```
memset(array, 0, sizeof(array))
```
But this only works for 1D arrays. When I printf the contents of the 2D array, the first row is zeroes, but then I got a load of random large numbers and it crashes.
|
```
memset(array, 0, sizeof(array[0][0]) * m * n);
```
Wheremandnare the width and height of the two-dimensional array (in your example, you have a square two-dimensional array, som == n).
|
The C faqs explain it in a way,here is the link.
But I can't understand it, Somebody can explain it for me? Or give me another way?
Thanks so much!
|
I think this example makes the answer clear:
```
struct test
{
int b;
int a;
};
int main()
{
test t;
test* structp = &t;
//Find the byte offset of 'a' within the structure
int offsetf = offsetof(test, a);
//Set the value of 'a' using pointer arithmetic
*(int *)((char *)structp + offsetf) = 5;
return 0;
}
```
|
I want to modify the registry of window OS using c. kindly guide me or give me some hints so that I can make it possible.
|
You need to use Win32 APIs such asRegOpenKeyExfor doing this.
|
in the Winsock2 librarygetaddrinfo()andfreeaddrinfo()was only added in Windows XP and on. I know how to replace them in legacy systems, but a conditional use depending on the Windows version won't help.
The application won't start in 9x with a message saying that it was linked to a missing export in WS2_32.dll.
I'm using MinGW to compile and link the code and would like to keep using it. Maybe writing those functions by myself?
Thank you very much for everything.
|
You can useLoadLibraryandGetProcAddressto (attempt to) get the addresses ofgetaddrinfoandfreeaddrinfo, then call them via the pointers iffGetProcAddressreturns a non-NULL pointer.
|
// File: foo.c
```
static int var;
void foo()
{
var++;
}
```
// end of file foo.c
// File bar.c:
```
static int var;
void bar()
{
var++;
}
```
// end of file bar.c
// file main.c
```
static int var;
void main()
{
foo();
bar();
printf("%d", var);
}
```
// end of file main.c
Question: Will the above program compile ? If so what will be the result ?
I tested the code and found it couldn't be compiled. I try to use extern in main.c to use the function foo() and bar() but it still couldn't be compiled.
|
main.c has a few minor problems - it should be something like this:
```
#include <stdio.h>
static int var;
extern void foo();
extern void bar();
int main(void)
{
foo();
bar();
printf("%d\n", var);
return 0;
}
```
It should build OK like this:
```
$ gcc -Wall main.c foo.c bar.c -o main
```
and the result should be:
```
$ ./main
0
```
|
Is there a way I can have a pad refresh to any window instead of (presumably)stdscr? I suppose I could temporarily changestdscrevery time I want to draw the pad, but that seems a little silly.
|
I just happened to have exactly same need for such function and I was more lucky: Trycopywinfunction, it should do what you need. However - unlikeprefresh- it doesn't do the refresh - you have to refresh the destination window yourself to display copied data.
http://nfosolutions.com/doc_link/C/a_doc_lib/libs/basetrf2/copywin.htm
|
I am looking at approaches to Unit Test embedded systems code written in C.
At the same time, I am also looking for a good UT framework that I can use. The framework should have a reasonably small number of dependencies.
Any great Open-source products that have good UTs?
EDIT:
Folks, thanks for the answers --Ireallyappreciate them, but this does notdirectlyanswer my question:
Do you know of any Open-source code that uses C Unit Tests? I am looking to see how it's done, so that I can learn something from the code...
|
Modularize your code in such a way that there is a thin layer in the bottom which knows about the details of the underlying hardware. That layer can then be mocked on a normal PC. That way you can use normal unit test libraries for desktop development to test all code except that thin bottom layer.
My experience on developing embedded software for Linux is using C++ and not plain C. We used cppunit for unit tests.
|
How to make a block of memory allocated by malloc() or new:
immediately swapped out,or lazily initialized.
In fact, I'm trying to reserve an address space. How to accomplish this?
PS. How to verify, from the user space, if a memory block is swapped out?
|
malloc is often implemented using mmap, so if you were to use malloc, you'd get the behavior you're after anyway. After all, why sould allocating memory force other pages out of cache when there's no guarantee that the new pages will be initialized immediately? I know that Open BSD implements malloc this way, and GNU's C lib uses mmap if your allocation is larger than some limit. I think it's just a couple pages.
I don't know about how Windows goes about all of this, but check the VirtualAlloc docs to see if it is specific about its purpose. If it documents that Windows' malloc caches its pages, then you have your answer and you should use VirtualAlloc.
|
I want to repeatedly zero a large 2d array in C. This is what I do at the moment:
```
// Array of size n * m, where n may not equal m
for(j = 0; j < n; j++)
{
for(i = 0; i < m; i++)
{
array[i][j] = 0;
}
}
```
I've tried using memset:
```
memset(array, 0, sizeof(array))
```
But this only works for 1D arrays. When I printf the contents of the 2D array, the first row is zeroes, but then I got a load of random large numbers and it crashes.
|
```
memset(array, 0, sizeof(array[0][0]) * m * n);
```
Wheremandnare the width and height of the two-dimensional array (in your example, you have a square two-dimensional array, som == n).
|
The C faqs explain it in a way,here is the link.
But I can't understand it, Somebody can explain it for me? Or give me another way?
Thanks so much!
|
I think this example makes the answer clear:
```
struct test
{
int b;
int a;
};
int main()
{
test t;
test* structp = &t;
//Find the byte offset of 'a' within the structure
int offsetf = offsetof(test, a);
//Set the value of 'a' using pointer arithmetic
*(int *)((char *)structp + offsetf) = 5;
return 0;
}
```
|
I want to modify the registry of window OS using c. kindly guide me or give me some hints so that I can make it possible.
|
You need to use Win32 APIs such asRegOpenKeyExfor doing this.
|
Why bitwise operation(~0);prints -1 ? In binary , not 0 should be 1 . why ?
|
You are actually quite close.
In binary , not 0 should be 1
Yes, this is absolutely correct when we're talking about one bit.
HOWEVER, anintwhose value is 0 is actually 32 bits of all zeroes!~inverts all 32 zeroes to 32 ones.
```
System.out.println(Integer.toBinaryString(~0));
// prints "11111111111111111111111111111111"
```
This is the two's complement representation of-1.
Similarly:
```
System.out.println(Integer.toBinaryString(~1));
// prints "11111111111111111111111111111110"
```
That is, for a 32-bit unsignedintin two's complement representation,~1 == -2.
Further reading:
Two's complementThis is the system used by Java (among others) to represent signed numerical value in bitsJLS 15.15.5 Bitwise complement operator~"note that, in all cases,~xequals(-x)-1"
|
I am using CreateProcess function for creating the process, is there any option to get the current state of the process (running or not). Kindly guide me how can I make it possible.
|
UseOpenProcessfunction with that dwProcessId if it returns NULL Process is not running otherwise it will return handle to that process
|
I have an enum declaration as:
```
enum qty { cars = 10, bikes = 9, horses = 9 ... } // total 28
```
How could I add up all the associated values of enumerator-list?
|
You can't know at runtime the contents of anenumin C.
Besides, this sounds like a misuse of enumerations. You should use them to defineconstantsthat you will use inside your code, not to store quantities or stuff like that which should otherwise bevariable: enumeration values are immutable. Use integer arrays for that purpose; you can loop through these.
|
Hello fellow software developers.
I want to distribute a C program which is scriptable by embedding the Python interpreter.The C program uses Py_Initialize, PyImport_Import and so on to accomplish Python embedding.
I'm looking for a solution where I distribute only the following components:
my program executable and its librariesthe Python library (dll/so)a ZIP-file containing all necessary Python modules and libraries.
How can I accomplish this? Is there a step-by-step recipe for that?
The solution should be suitable for both Windows and Linux.
Thanks in advance.
|
Have you looked at Python's official documentation :Embedding Python into another application?
There's also this really nice PDF by IBM :Embed Python scripting in C application.
You should be able to do what you want using those two resources.
|
Is there a windows API to get the number of colors currently set on the display settings? What I mean is, if you look at the windows display setting you might get something like:
resolution: 1280x800
colors: 1,000,000
I am using a call to WMI (Win32_VideoController) and get them from there, but I can't use this since the program cannot use WMI.
Is there an API or other way (the registry maybe?) to get the number of colors the system supports?
code is appreciated, thanks!
|
GetDeviceCapswith theBITSPIXELoption is what you're looking for
|
```
void* ptr1 = NULL;
void* ptr2 = ptr1;
unsigned int *buf = data;//some buffer
//now
ptr2 = buf + 8;
```
The above change in address of ptr2 is not reflected in ptr1.
I am tryingvoid* ptr2 = &ptr1;too.
Please let me know whats the mistake here.
|
Why would ptr1 follow ptr2?
If you wanted ptr1 to have the same address as ptr2 then you would set it to ptr2:
```
ptr1 = ptr2;
```
In your post ptr1 still points to NULL. So you need to explicitly tell it to point to ptr2.
Drawing pictures makes it all the more clearer so go at it:
alt text http://img705.imageshack.us/img705/2433/pointers.png
Right now you have 2 pointers pointing at some data or no data (NULL). If you want a pointer to follow another pointer, you want a pointer to a pointer (2 asterisks) not just a pointer (1 asterisk).
```
void** ptr1 = (void**) &ptr2;
```
|
i want to use the dos commands in my ansi-c program how can i do so what type of lib or .h i will need for it if it is possible ?
|
Use thesystemfunction, fromstdlib.h.
Here is Wikipedia documentation of this function
|
```
#include<stdio.h>
#include<conio.h>
#define ABC 20
#define XYZ 10
#define XXX ABC - XYZ
void main()
{
int a;
a = XXX * 10;
printf("\n %d \n", a);
getch();
}
```
I thought the output should be 100 but when I saw the result I found output as -80. When I put brackets as#define XXX (ABC-XYZ)then I get output as 100 but without brackets I get output as -80.
|
The preprocessor is a dumb beast. It works on a purely textual level, without regard for what it's doing to the code semantically. Let's see what it does in this case:
```
a = XXX * 10;
```
becomes
```
a = ABC - XYZ * 10;
```
which becomes
```
a = 20 - 10 * 10;
```
which is, obviously,-80.
What was probably intended was
```
#define XXX (ABC - XYZ)
```
This is one reason why macros are considered evil.
|
Is there any option to call msi file from CreateProcess in c language in window OS.
|
The WindowsShellExecute functionwill open a file of a registered type with the correct application, which I think is what you are asking about.
|
When I do a release build with gcc (i.e. I do not specify-g), I still seem to end up with symbols in the binary, and have to usestripto remove them. In fact, I can still breakpoint functions and get backtraces in gdb (albeit without line numbers).
This surprised me - can anyone explain why this happens?
e.g.
```
#include <stdio.h>
static void blah(void)
{
printf("hello world\n");
}
int main(int argc, char *argv[])
{
blah();
return 0;
}
```
gcc -o foo foo.c
nm foo | grep blah:
08048374 t blah
|
There's a big difference between debug symbols and linker symbols. Debug symbols map code locations etc to source file names and line numbers and various other useful things to help debuggers, profilers, etc. Linker symbols just define the addresses of various entry points and other important locations in your code. If you want to make an executable completely anonymous then you need to usestrip, as you have seen.
|
try it out:
```
volatile float bob = -344.0f;
unsigned int fred = (unsigned int)bob;
printf("%d\n",fred);
```
output will be 0.
obviously I am expecting it to wrap around just as if I had cast from a signed int to an unsgined int (which does wrap and act as expected on the iphone)
we assume it is something to do with the floating point settings.
any ideas?
|
This is to be expected - casting a negative float to an unsigned int results in undefined behaviour (UB). If you want the value to wraparound (which is also UB, BTW), then you would need to cast to a (signed) int first and then to unsigned int. Ideally you should not rely on UB at all and find a better way of doing what you need to do.
|
When running the following code I get no output but I cannot work out why.
```
# include <stdio.h>
int main()
{
fputs("hello", stdout);
while (1);
return 0;
}
```
Without the while loop it works perfectly but as soon as I add it in I get no output. Surely it should output before starting the loop? Is it just on my system? Do I have to flush some sort of buffer or something?
Thanks in advance.
|
You have to flushstdout. This happens automatically when you write a newline character. Change thefputsto:
```
fputs("hello\n", stdout);
```
Or to:
```
fputs("hello", stdout);
fflush(stdout);
```
|
Does anyone have code snippet for Triple DES algorithm in C ?
Thanks
|
OpenSSLis written in C and provides a 3DES algorithm. It may not be as simple as some of the other suggestions, but it may be worth checking out.
|
How can I encrypt and decrypt a file with a 256 key AES in C or C++?
|
If you are just after AES and do not mind losing flexibility (i.e. you will not replace it with another cryptographic algorithm at some time) thenBrian Gladman's AES implementationis a popular choice (both for performance and portability). This is the kind of code which you embed in your own source code.
On the external libraries front, you have plenty of choice, includingNSS,OpenSSL,Crypto++... the latter is specifically designed for C++, while the two others are meant for C.
|
I tried to implement the strcat by myself, and I found the strcat implementation fromWikilike this......but when I use it, there is segmentation fault.
What's wrong with the code below?
```
char *
strcat(char *dest, const char *src)
{
size_t i,j;
for (i = 0; dest[i] != '\0'; i++)
;
for (j = 0; src[j] != '\0'; j++)
dest[i+j] = src[j];
dest[i+j] = '\0';
return dest;
}
```
|
the code is okay.
Looks like you have a problem in the calling code.
Did you remember to allocate enough memory for the target string?
|
I'm a beginner at C, and using Turbo C++ compiler (16 bit).
In the software I'm writing, the maximum answer is around 32000. If I want a number larger than that, I uselong int.
If I execute the following program:
```
#include <stdio.h>
void main()
{
long int x;
x=40000;
printf("%d", x);
}
```
Then I get an error that the constant value is long in functionmain().
How can I get an answer more that 32000 and get rid of this error?
also nw i change %d to %ld and use 40000L bt when i use unsigned integer then also i need to use 'l' with 40000//??
|
Use %ld in printf for the long int. %d is for int which only has 16 bits in your compiler. And for the error message, use x=40000L.
|
How can I encode a file using sha256 and c/c++ ???
Thanks!
|
SHA 256stands for Secure Hash Algorithm ! It will only produce the hash of a given file . You can't retrieve the original file from a given hash otherwise hash functions are useless.
If you want to do encryption/decryptionAESwould be a better solution. Everything you need is inOpenSSL.
|
I have a loop which basically calls this every few seconds (after the timeout):
```
while(true){
if(finished)
return;
switch(select(FD_SETSIZE, &readfds, 0, 0, &tv)){
case SOCKET_ERROR : report bad stuff etc; return;
default : break;
}
// do stuff with the incoming connection
}
```
So basically for every few seconds (which is specified by tv), it reactivates the listening.
This is run on thread B (not a main thread). There are times when I want to end this acceptor loop immediately from thread A (main thread), but seems like I have to wait until the time interval finishes..
Is there a way to disrupt the select function from another thread so thread B can quit instantly?
|
The easiest way is probably to usepipe(2)to create a pipe and add the read end toreadfds. When the other thread wants to interrupt theselect()just write a byte to it, then consume it afterward.
|
I'd like to be able to write a time string that looks like this:1:04:02.1 hoursusing printf.When I try to write something like this:
```
printf("%d:%02d:%02.1f hours\n", 1, 4, 2.123456);
```
I get:
```
1:04:2.1 hours
```
Is it possible to add leading zeros to a float formatting?
|
With the%fformat specifier, the "2" is treated as the minimum number of characters altogether, not the number of digits before the decimal dot. Thus you have to replace it with 4 to get two leading digits + the decimal point + one decimal digit.
```
printf("%d:%02d:%04.1f hours\n", 1, 4, 2.123456);
```
|
I need to do a simple thing, which I used to do many times in Java, but I'm stuck in C (pure C, not C++). The situation looks like this:
```
int *a;
void initArray( int *arr )
{
arr = malloc( sizeof( int ) * SIZE );
}
int main()
{
initArray( a );
// a is NULL here! what to do?!
return 0;
}
```
I have some "initializing" function, which SHOULD assign a given pointer to some allocated data (doesn't matter). How should I give a pointer to a function in order to this pointer will be modified, and then can be used further in the code (after that function call returns)?
|
You need to adjust the *a pointer, this means you need to pass a pointer to the *a. You do that like this:
```
int *a;
void initArray( int **arr )
{
*arr = malloc( sizeof( int ) * SIZE );
}
int main()
{
initArray( &a );
return 0;
}
```
|
I have a simple gateway listener which generates a log at the screen output via printf. I would like to record it so I can insert it in a mysql table.
```
printf("\nPacket received!! Decoding...");
```
I wonder if there is any fast way to do this is C.
In case there is, could I get both outputs at the same time?
Thanks
|
I'm not aware of any function that does output buffering in C. But you can simulate one easily like:
```
char buffer[MAX_BUFFER_SIZE] = ""; // that buffers your output.
char temp[SOME_SUITABLE_MAX];
```
now everytime you are usingprintf, use asprintfas follows:
```
sprintf(temp,"\nPacket received!! Decoding...");
```
and them append this string to the buffer
```
strcat(buffer,temp);
```
keep doing thesprintffollowed bystrcatfor every message you want to buffer and once done buffer will have the buffered output.
|
Is it possible to access the "errno" variable in C# when P/Invoking? This is similar to Win32 GetLastError().
|
I'm fairly sure that there is a way, but it probably is a bad idea. How would you guarantee that the runtime has not called some CRT function during its internal processing that has affected theerrno?
For the same reason, you should not callGetLastErrordirectly either. TheDllImportAttributeprovides aSetLastErrorproperty so the runtime knows to immediately capture the last error and store it in a place that the managed code can read usingMarshal.GetLastWin32Error.
I think the most robust thing you could do in this case is make a C DLL that performs both the actual C work and the capture of theerrno. (Note that just writing a wrapper around theerrnocapture would still have the concerns mentioned above.)
|
```
#include<stdio.h>
void function(int);
int main()
{
int x;
printf("Enter x:");
scanf("%d", &x);
function(x);
return 0;
}
void function(int x)
{
float fx;
fx=10/x;
if(10 is divided by zero)// I dont know what to put here please help
printf("division by zero is not allowed");
else
printf("f(x) is: %.5f",fx);
}
```
|
```
#include<stdio.h>
void function(int);
int main()
{
int x;
printf("Enter x:");
scanf("%d", &x);
function(x);
return 0;
}
void function(int x)
{
float fx;
if(x==0) // Simple!
printf("division by zero is not allowed");
else
fx=10/x;
printf("f(x) is: %.5f",fx);
}
```
|
I've been looking at Boost and various other C++ libraries. The vast majority of Boost is implemented in header files.
My question is: under what conditions do you do a header-only implementation (like Boost) or also include a .cpp file?
|
If you want to use a template in another translation unit (i.e. another source file), you should (almost always) define it in the header file. (There are exceptions, like the comments below point out, but IMHO this is a good rule of thumb.)
Same applies if you want to use an inline function from another translation unit.
Otherwise you should put the implementation into a separate .cpp file to minimize dependencies.
|
Can anyone explain the difference between a fork and a thread?
|
A fork gives you a brand new process, which is a copy of the current process, with the same code segments. As the memory image changes (typically this is due to different behavior of the two processes) you get a separation of the memory images (Copy On Write), however the executable code remains the same. Tasks do not share memory unless they use someInter Process Communication (IPC)primitive.
One process can have multiple threads, each executing in parallel within the same context of the process. Memory and other resources are shared among threads, therefore shared data must be accessed through some primitive and synchronization objects (likemutexes,condition variablesandsemaphores) that allow you to avoid data corruption.
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.