question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I don't recall seeing any program callsrandwith anything butsrand(time(NULL)). Under what circumstances would one callsrandwith some other value?
|
The functionrand()doesn't return random numbers. It's apseudorandom generator instead. That's why you get the same sequence of numbers when you callsrand()with the same argument. Callingsrand()with the current time is the actually only random item. The numbers you get fromrand()are just scrambled.
You will callsrand(... |
```
void main()
{
int i,sample;
clrscr();
for(i=0;i<5;i++)
{
sample=rand();
printf("%d\n",sample);
}
getch();
}
```
For the above code, every time I execute, the same random numbers 346,130,10982,1090,11656 are generated. But I need to generate varying random numbers when I execute the c... |
Use arandom seedthat changes each time you run the program. One common approach is to use the current time.
```
srand(time(NULL));
```
|
I have two header files named Secure.h and FileMgt.h. To encrypt the File while saving i use Secure.h in FileMgt.h and in FileMgt.h i have declared some structure which is needed by Secure.h.The FileMgt.h is again include in another file called ElecB.h. I have used header guards in all the Files. The Problem is FileMg... |
Declare the structure in a third header file (with include guards) and include it in both Secure.h and FileMgt.h
|
I have following piece of code where I am getting an error of
error: expected expression before const (at line 15)
```
12 : int
13 : function1(const char *arg1, const char **arg2)
14 : {
15 : int i = function2(const char *arg1, const char **arg2);
16 : }
18 : int
20 : function2(const char *arg1, const ... |
Removeint i = function2(const char *arg1, const char **arg2);Withint i = function2(arg1,arg2);
Your variables are already defined.
when calling to function in C you shouldn't say parameters type , you have to pass parameters themselves.
|
Is it ok or can it be considered a bad practice to return nonconstdata member pointer from aconst struct? What are the dangers of returning a nonconstpointer as shown below?
```
widget_t * widget_child(const widget_t * parent)
{
if (!parent)
return NULL;
return parent->child;
}
```
|
Whether it is acceptable to return a specific non-constdata member from aconst-qualifiedstructdepends entirely on the semantics of the data-structure it is a part of.It is not legally wrong, and C cannot say anything more on the subject.You, as the programmer, who (hopefully) knows and understands the semantics are tr... |
My code accidentally ends up with the following structure. Im not sure that is this ok.
```
switch (msg.type)
{
case Msg::Type::One:
case Msg::Type::Two:
// do nothing
break;
case Msg::Type::Open:
if (msg.isBad())
break;
else // opened else branch is ok here??
// intended fall through... |
It may work, but if you intend to fall through, I would just remove the else altogether, and leave a comment that it is an intentional fall through.
|
i have looked for an answer and have not found one.
```
@echo off
:a
cls
set /p %a% =
if %a% == 1 goto b
goto c
:b
echo.
echo worked
pause
:C
echo.
echo dident work
pause
```
i set a = 1 and is said that the goto command was unexpected at this time. any help would be great
Changed
ok it has been change and a new p... |
```
@echo off
echo.
set /p a=
echo.
if %a%==1 goto b
if not %a%==1 goto c
:b
echo worked
echo.
pause
exit
:c
echo dident work
echo.
pause
exit
```
|
on page 23 in the K&R second edition, there is some code
```
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
```
It goes on. My question is, why do the integers have the ' on each side?
and what is the c-'0'?
|
'0'is a character. It has the integer value 48.'9'has the value 57. The value ofc - '0'is equal toc - 48, and will be the integer value of the corresponding character.'0'will be0,'1'will be1, etc.
|
This question already has answers here:Segmentation Fault in strcpy()(3 answers)Closed8 years ago.
```
struct Object * newObj(char * nome, int idade, float altura) {
struct Object *obj = (struct Object *) malloc(sizeof(struct Object));
strcpy(obj->nome, nome); // This is the line
obj->idade = idade;
o... |
In yourstruct Objecttype, thenomemember is declared as a pointer and you also need to allocate memory for the array. Without allocating memoryobj->nomehas an inderminate value.
|
I was asked to do the following:
Print "Enter an integer and string"Scan the integer and string
The integer in this case represent's the string's length (I can assume correctness of input). The thing is, I cannot figure out how to both recieve a length and then allocate memory for the string of that length and then ... |
Even though the data is entered all in one line, you don't have to read it all at the same time:
```
scanf("%d",&length);
str = malloc(length+1);
scanf("%s",str);
```
Each time use use scanf, it just reads as much as it can, and leaves the rest in the input buffer.
|
i have looked for an answer and have not found one.
```
@echo off
:a
cls
set /p %a% =
if %a% == 1 goto b
goto c
:b
echo.
echo worked
pause
:C
echo.
echo dident work
pause
```
i set a = 1 and is said that the goto command was unexpected at this time. any help would be great
Changed
ok it has been change and a new p... |
```
@echo off
echo.
set /p a=
echo.
if %a%==1 goto b
if not %a%==1 goto c
:b
echo worked
echo.
pause
exit
:c
echo dident work
echo.
pause
exit
```
|
on page 23 in the K&R second edition, there is some code
```
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
```
It goes on. My question is, why do the integers have the ' on each side?
and what is the c-'0'?
|
'0'is a character. It has the integer value 48.'9'has the value 57. The value ofc - '0'is equal toc - 48, and will be the integer value of the corresponding character.'0'will be0,'1'will be1, etc.
|
This question already has answers here:Segmentation Fault in strcpy()(3 answers)Closed8 years ago.
```
struct Object * newObj(char * nome, int idade, float altura) {
struct Object *obj = (struct Object *) malloc(sizeof(struct Object));
strcpy(obj->nome, nome); // This is the line
obj->idade = idade;
o... |
In yourstruct Objecttype, thenomemember is declared as a pointer and you also need to allocate memory for the array. Without allocating memoryobj->nomehas an inderminate value.
|
I was asked to do the following:
Print "Enter an integer and string"Scan the integer and string
The integer in this case represent's the string's length (I can assume correctness of input). The thing is, I cannot figure out how to both recieve a length and then allocate memory for the string of that length and then ... |
Even though the data is entered all in one line, you don't have to read it all at the same time:
```
scanf("%d",&length);
str = malloc(length+1);
scanf("%s",str);
```
Each time use use scanf, it just reads as much as it can, and leaves the rest in the input buffer.
|
I have a server (in c on windows) just listen on many sockets.
I have to detect if some of those sockets doesn't send data from more than xx minutes.
And in that case I have to close that specific connection.
I have studied keep alive parameter but I have not still idea how to implement this requirement.
Thanks
Ro... |
Define astructcontaining a socket handle and a timestamp of the last time data was received on that socket. When a client connects, put it in a list/array and set the timestamp. When a client disconnects (or you close it), locate that socket in the list/array and remove it. Each time new data is received, locate th... |
Is it possible in anyway to recursively create a given number of arrays in C with predetermined length? I want to experiment with arrays for a clustering project and would be really practical if i could do this.
|
Yes it is possible, allocate an array of pointers then allocate all the arrays:
```
T **array = malloc(rows * sizeof *array);
for (i = 0; i < rows; i++)
{
array[i] = malloc(cols * sizeof **array);
}
```
it createrowsnumbers of array. Each array is an array ofcolsnumbers ofT.
|
I have downloaded a SHA-1 function, by Paul E. Jones, from the web.
This code is going into a medical device as SOUP (Software Of Unknown Provenance) and needs to be verified.
Is there an official website that can be used to verify a C implementation of the SHA-1 algorithm?
Here's a link to the SHA-1 implementation... |
Thanks to Nickolay Olshevsky for the Test Vector guidance and to Daniel Kamil Kozar for the link.
The method to validate the algorithm is to feed it known test vectors and compare the digest to known digests from the NIST library:NIST Library
The best process for testing would be to send the algorithm on the platfor... |
i have this code to split an unsigned 32 bit integer into a char array with each element of the array relating to 8 bits of the integer:
```
unsigned char result[4];
result[0] = (value >> 24) & 0xFF;
result[1] = (value >> 16) & 0xFF;
result[2] = (value >> 8) & 0xFF;
result[3] = value & 0xFF;
```
what changes would i... |
Dont call them the first/last bits. Refer to them by their significance.
```
unsigned short result[3];
result[0] = (value >> 24) & 0xFF;
result[1] = (value >> 16) & 0xFF;
result[2] = value & 0xFFFF;
```
|
I need to identify if I am at the top of the file just wondering for binary files do they have something similar to eof at the top ?
|
A file does not contain "EOF" at all.EOFis just a special value returned fromfgetc()and other functions when they detect the end of the file. The end of the file is detected through other means, such as byread()returning 0 (or returning less than the requested number of bytes, if you are reading a regular file).
If ... |
Given the following method
```
void fillArray(void *arr, int const numElements, void *val, int size)
```
How can you fill an array (*arr) with a value (*val) without knowing what type the array ?numElementsis the number of elements that are in the array and size is the byte size of whatever type the array is.
|
You can usememcpyfor that. However, in order to advance the memory location, you have to cast input pointer to achar*first. If you havevoid*, the pointer arithmetic operations are not defined.
```
void fillArray(void *arr, int const numElements, void *val, int size)
{
char* cp = arr;
int i = 0;
for ( ; i < n... |
I have a code that is supposed to get the time , I want to store the time in my char array but I cannot do that so , I thought that I could have a loop to a pointer and loop through the pointer and copy the chars from the pointer memory to my char, is that possible?
```
void My_Time(char *myt_Time,int size)
{
ti... |
From what I understand of your problem, the following code should work, instead of yourforloop.
strncpy(myt_Time, mytTemp, size);
The bug in yourforloop is there:
myt_Time[x]=myt_Temp;=>myt_Time[x]=myt_Temp[x];
|
```
typedef char string20[21];
struct x{
string20 a;
string20 b;
string20 c;
};
```
How do I scan a text file and store their values on my structure? I can't think of an easy way on how to do this and btw I'm just learning I/O can't find any good tutorial on internet please help
the file format is:
```
3
FCODE=rand... |
Usefgetsfunction to a single line.
```
eg: fgets(buf, MAX_LINE_SIZE, my_io);
```
Usestrchrorstrtokto find exact data.
```
eg: ptr = strchr(buf, '=');
```
copy into your structure
```
eg: strcpy(my_structy.ele, ptr);
```
PS: don't forget validations. refer man pages
|
So C/C++ arrays don't know about their length, right? But then how can the functionsizeof(array)work and give us the proper size in bytes when it shouldn't be able to know the number of elements in the array?
|
So C/C++ arrays don't know about their length, right.
Your assumption is wrong. With the exception of variable length arrays introduced in C99, arrays in both C and C++ have a size that is known in compile time. The compiler knows their size.
Your confusion is probably because there are times when array names decay ... |
I have a server (in c on windows) just listen on many sockets.
I have to detect if some of those sockets doesn't send data from more than xx minutes.
And in that case I have to close that specific connection.
I have studied keep alive parameter but I have not still idea how to implement this requirement.
Thanks
Ro... |
Define astructcontaining a socket handle and a timestamp of the last time data was received on that socket. When a client connects, put it in a list/array and set the timestamp. When a client disconnects (or you close it), locate that socket in the list/array and remove it. Each time new data is received, locate th... |
Is it possible in anyway to recursively create a given number of arrays in C with predetermined length? I want to experiment with arrays for a clustering project and would be really practical if i could do this.
|
Yes it is possible, allocate an array of pointers then allocate all the arrays:
```
T **array = malloc(rows * sizeof *array);
for (i = 0; i < rows; i++)
{
array[i] = malloc(cols * sizeof **array);
}
```
it createrowsnumbers of array. Each array is an array ofcolsnumbers ofT.
|
I have downloaded a SHA-1 function, by Paul E. Jones, from the web.
This code is going into a medical device as SOUP (Software Of Unknown Provenance) and needs to be verified.
Is there an official website that can be used to verify a C implementation of the SHA-1 algorithm?
Here's a link to the SHA-1 implementation... |
Thanks to Nickolay Olshevsky for the Test Vector guidance and to Daniel Kamil Kozar for the link.
The method to validate the algorithm is to feed it known test vectors and compare the digest to known digests from the NIST library:NIST Library
The best process for testing would be to send the algorithm on the platfor... |
i have this code to split an unsigned 32 bit integer into a char array with each element of the array relating to 8 bits of the integer:
```
unsigned char result[4];
result[0] = (value >> 24) & 0xFF;
result[1] = (value >> 16) & 0xFF;
result[2] = (value >> 8) & 0xFF;
result[3] = value & 0xFF;
```
what changes would i... |
Dont call them the first/last bits. Refer to them by their significance.
```
unsigned short result[3];
result[0] = (value >> 24) & 0xFF;
result[1] = (value >> 16) & 0xFF;
result[2] = value & 0xFFFF;
```
|
I need to identify if I am at the top of the file just wondering for binary files do they have something similar to eof at the top ?
|
A file does not contain "EOF" at all.EOFis just a special value returned fromfgetc()and other functions when they detect the end of the file. The end of the file is detected through other means, such as byread()returning 0 (or returning less than the requested number of bytes, if you are reading a regular file).
If ... |
I understand that
```
char* a = "hello";
char* b = "olleh";
strcpy(a,b)
```
will copy the contents of b to a, but what about...
```
char* a = "hello";
char* b = "olleh";
a = b;
```
I was erroneously doing this previously. I was wondering what does the=operator do in this case for strings?
|
strcpy copies the string, by looking at the location of the pointer and copying characters until it copies a null terminator. a and b will point to different strings with the same contents.
a = b is pointer assignment, so a and b will then both point to the SAME memory containing the string "olleh".
|
What is the total amount of memory necessary (in Bytes) to create a 4 x 3 x 3 array of doubles dynamically?
I know the answer is 356 but simply do not understand where the extra bytes are coming from. A lille help please?
|
So as @user4815162342 says, you need at least 288 bytes for doubles but he/she didn't say nothing about extra 68 bytes for 17 pointers. This makes 356 bytes. 32 bit integers assumed as pointers.1. You need 1 pointer to the entire array.2. Then 4 pointers on the second dimension.3. Finally 12 pointers on the third dime... |
I have a View Controller with aUICollectionView. EachUICollectionViewCellhas oneUILabeland oneUIButton. How can I print the text of eachUILabelin theUICollectionViewwhen clicking the correspondingUIButton.
|
If I understood you right, you can subclass yourUICollectionViewCell, linkUILabelto corresponding property and create a method forUIButtontouch. Here is the sample code of this method:
```
@interface MyCustomCollectionViewCell: UICollectionViewCell
@property (weak, nonatomic) IBOutlet UILabel *cellLabel;
- (void)cel... |
Can anyone help me to understand the meaning of this line?
I know it's kind of macro structure, but what does , suggest in the code??
```
#define ReturnErr(fCall) if (iErr = (fCall), (iErr != NO_ERRORS)) {return iErr;}
```
|
A qualified guess is that the macro is meant to be used like this:
```
err_t func (void)
{
err_t iErr;
ReturnErr(some_function());
...
return NO_ERRORS;
}
```
In that case the macro expands to:
```
err_t func (void)
{
err_t iErr;
if(iErr = some_function(), iErr != NO_ERRORS) { return iErr; }
...
... |
I am just working on a simple client and server program in c.
I have realized that in order to use sockets I have to link the winsock libary file with a pragma: #pragma comment(lib, "Ws2_32.lib").
I was wondering if there is another why to do it without using the pragma instruction. Thanks a lot in advance.
|
You can add library directly in project.
Follow the steps.
Step 1:Go to project settings in linker option in Additional dependency add your library name like Settings->linker->Additional dependency : add your library name.
Step 2:Settings->linker->Additional Library Dependency : add your library .lib path.(Ignore i... |
consider the following example:
```
typedef enum {Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday} Day;
void DoSomething(Day day){
//some code
}
```
The problem is that the following code complies:DoSomething(74). So how can I check in DoSomething that my parameter is really a Day?
(relying on numbers won't... |
The short answer is you can't.
The long answer is you can try to put a "minimum" and a "maximum" member, and check that the value falls in the range between the two... or some other similar trick.
|
I have embedded CLIPS into C Language program, I want to modify the facts for example change a certain slot value, which function can I use from C language Program. Otherwise I have to clean all the facts and assert new facts to implement my goal.
Thanks for any idea and suggestions
|
Section 4.4 of the Advanced Programming Guide,http://clipsrules.sourceforge.net/OnlineDocs.html, has a list of functions that can be used on facts. The fact-set queries and distributed actions in section 12.9.12 of the Basic Programming Guide are also useful for retrieving and manipulating facts from a C program. For ... |
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question
i am running 3 application at same time in different console , all 3 application are dependent to each othe... |
run your script in background with linuxnohupcommand.
```
nohup applicationName &
```
|
I have come across a problem involving exclamation marks and integers whilst reading a code in my reference book.
Let us say I have declared an integer variable named number -int number = 0;
I then use a while function involving an exclamation mark andnumber
```
while(!number)
{
...
}
```
I am confused with th... |
We can treat!as not.
So if a number is non-zero (either positive or negative) it returns Zero.
If it is zero, it returns 1.
```
int i = 13;
printf("i = %d, !i = %d\n", i, !i);
printf("!0 = %d\n", !(0));
```
|
I have the following c code
```
if (sscanf(input, "s %d\n", &value) == 1){}
```
Where it is suppose to parse the following
```
s -inf
....
s 0
s 1
s 2
....
s inf
```
but not such things as
```
s 5junkjunkjunk
```
Because it shouldn't match as there is something in between%dand the\n. Yet it does work even though... |
This is (one of the) reasons why one should never use*scanf: it's ridiculously difficult to get it to handle malformed input robustly.
The correct way to parse something like this is: usefgets(orgetlineif you have it) to read an entire line, manually check for and skip over the leading"s ", then usestrtodto parse the... |
So, I'm having problems with my parser.y with a compiler that I'm building. The error is saying I don't have a member inside of a union or structure, which it is. Here is the error code I've received:
```
parser.y:123: error: request for member ‘funcName’ in something not a structure or union
```
Then with the code ... |
The tokens have the type of whichever union member you assigned to them with the%tokendeclaration - not the union type itself. So$2has typechar*and you don't need the.funcName- it already holds the value of thefuncNamemember.
|
So I made a program where it assigns each card from a deck of cards into an array. I was required to make a shuffle function, displayCard function, and also a dealCard function. What I'm really confused on is thedealCardfunction. I don't get the concept of dealing/ take a card from the deck and no longer having it int... |
Rather then view the deck of cards aschar deck[SIZE], re-define the deck of cards as
```
char deck[SIZE];
int deck_count;
```
Or as a structure:
```
typedef struct {
char deck[SIZE];
int n;
} stock;
```
Then create functions to manipulate the stock:
```
void stock_newdeck(stock *st); // fresh deck of 52 card... |
I have the following c code
```
if (sscanf(input, "s %d\n", &value) == 1){}
```
Where it is suppose to parse the following
```
s -inf
....
s 0
s 1
s 2
....
s inf
```
but not such things as
```
s 5junkjunkjunk
```
Because it shouldn't match as there is something in between%dand the\n. Yet it does work even though... |
This is (one of the) reasons why one should never use*scanf: it's ridiculously difficult to get it to handle malformed input robustly.
The correct way to parse something like this is: usefgets(orgetlineif you have it) to read an entire line, manually check for and skip over the leading"s ", then usestrtodto parse the... |
So, I'm having problems with my parser.y with a compiler that I'm building. The error is saying I don't have a member inside of a union or structure, which it is. Here is the error code I've received:
```
parser.y:123: error: request for member ‘funcName’ in something not a structure or union
```
Then with the code ... |
The tokens have the type of whichever union member you assigned to them with the%tokendeclaration - not the union type itself. So$2has typechar*and you don't need the.funcName- it already holds the value of thefuncNamemember.
|
So I made a program where it assigns each card from a deck of cards into an array. I was required to make a shuffle function, displayCard function, and also a dealCard function. What I'm really confused on is thedealCardfunction. I don't get the concept of dealing/ take a card from the deck and no longer having it int... |
Rather then view the deck of cards aschar deck[SIZE], re-define the deck of cards as
```
char deck[SIZE];
int deck_count;
```
Or as a structure:
```
typedef struct {
char deck[SIZE];
int n;
} stock;
```
Then create functions to manipulate the stock:
```
void stock_newdeck(stock *st); // fresh deck of 52 card... |
Is there a linux command that would allow you to print out the C code in the GCC header file for a specific function? For example inputting strncpy and the output would be the C code held within it. Or is the code comprised of only assembly code or something? I believe I have seen such a thing before but cannot find a... |
Generally, there is no way to do that. Yes, a library linked with yourCcode could be written in assembly, or many other languages. The source code of the libraries are not needed to use them, so there is no such tool. You need to look for the sources yourself.
|
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *a = "kitty";
const int a_length = strlen(a);
char *my_kitty = malloc(a_length);
strcpy(my_kitty, a);
printf("%s\n", my_kitty);
return EXIT_SUCCESS;
}
```
What is wrong with this code? Null check for malloc... |
Don't forget to allocate an extra +1 for the null terminator!
```
char *my_kitty = malloc(a_length + 1);
... strcpy()
```
my_kitty[a_length] = 0;
(as per the comments,strcpywill also copy the null terminator)
Edit
Just be carefulwhen using eitherstrcpyorstrncpy- the former is prone to buffer overflows if the null... |
If I map a page as write only:
```
int* mem_location = (int*)mmap(nullptr, getpagesize(),
PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
cout << "Read @" << mem_location << ". This should segfault: "
<< *mem_location << endl;
cout << "doesn't though??" << endl;
```
why doesn't it segfault on read?
|
See theman page:
On some hardware architectures (e.g., i386), PROT_WRITE implies PROT_READ.
You should not depend on this behavior.
|
Other than using any inbuilt function likeceilandfloorhow can you round a floating point number?
I want to convert 2.10 to 2.14-> 2.1 and 2.15 to 2.19 -> 2.2
I wrote some logic but stuck in the middle
```
float a = 2.24;
int b = a*100;
int result n, i =0;
while(i>2)
{
n = b%10;
i++;
... |
```
float a = 2.24;
float b = roundf(a*10.0f)/10.0f;//roundf in C99
```
|
This question already has answers here:Convert char with hex value to String(2 answers)Closed9 years ago.
I'm getting a bunch of hex characters from a peripheral which I then want to print into a txt file as a string. I've found loads of examples of people converting hex into ascii string such as 0x5A in "Z" but can'... |
If you want to print avaluein hex just use the%xformat specifier withprintf, e.g.
```
uint8_t n = 0x5a;
printf("%x\n", n); // 5a
printf("%#x\n", n); // 0x5a
```
(Note that%#xgives you an0xprefix on your hex value.)
|
In C, how can you generate uniformly distributed (double) numbers within a range of [-1,1], [-2,2] and so on?
|
Includes:
```
#include <time.h>
#include <stdlib.h>
```
Needed somewhere in beginning:
```
srand(time(NULL));
```
And function:
```
double Rand(double min, double max)
{
return rand() / (double)(RAND_MAX - 1) * (max - min) + min;
}
```
So you can call this something like:
```
Rand(-2, 2);
```
Or make ano... |
I have parsed a date in C with strptime.
Now I have something like this:
```
debugLog(DEB_INFO, "observationDateConverted: %d-%d-%d %d:%d:%d\n",
result.tm_year+1900,
result.tm_mon + 1,
result.tm_mday,
result.tm_hour, ... |
General approach: Turn the struct tm into a timestamp (64bit int) and then add millis/1000.
```
time_t totalseconds = mktime(&result) + (millis / 1000);
```
You can then use the functions fromC's time APIto convert the time stamp back tostruct tm.
|
I want to do a screenshot of a GUI window from C/C++ into the memory.
It would be really nice if it's a two dimension array of RGB values or something similar.
Im at the moment searching for a Linux based solution, but would be nice if there is a platform independent solution.
|
You could utilizexlibfor Linux:How do take a screenshot correctly with xlib?
AndGDIon Windows:MSDN - Capturing an Image
|
Other than using any inbuilt function likeceilandfloorhow can you round a floating point number?
I want to convert 2.10 to 2.14-> 2.1 and 2.15 to 2.19 -> 2.2
I wrote some logic but stuck in the middle
```
float a = 2.24;
int b = a*100;
int result n, i =0;
while(i>2)
{
n = b%10;
i++;
... |
```
float a = 2.24;
float b = roundf(a*10.0f)/10.0f;//roundf in C99
```
|
This question already has answers here:Convert char with hex value to String(2 answers)Closed9 years ago.
I'm getting a bunch of hex characters from a peripheral which I then want to print into a txt file as a string. I've found loads of examples of people converting hex into ascii string such as 0x5A in "Z" but can'... |
If you want to print avaluein hex just use the%xformat specifier withprintf, e.g.
```
uint8_t n = 0x5a;
printf("%x\n", n); // 5a
printf("%#x\n", n); // 0x5a
```
(Note that%#xgives you an0xprefix on your hex value.)
|
In C, how can you generate uniformly distributed (double) numbers within a range of [-1,1], [-2,2] and so on?
|
Includes:
```
#include <time.h>
#include <stdlib.h>
```
Needed somewhere in beginning:
```
srand(time(NULL));
```
And function:
```
double Rand(double min, double max)
{
return rand() / (double)(RAND_MAX - 1) * (max - min) + min;
}
```
So you can call this something like:
```
Rand(-2, 2);
```
Or make ano... |
I have parsed a date in C with strptime.
Now I have something like this:
```
debugLog(DEB_INFO, "observationDateConverted: %d-%d-%d %d:%d:%d\n",
result.tm_year+1900,
result.tm_mon + 1,
result.tm_mday,
result.tm_hour, ... |
General approach: Turn the struct tm into a timestamp (64bit int) and then add millis/1000.
```
time_t totalseconds = mktime(&result) + (millis / 1000);
```
You can then use the functions fromC's time APIto convert the time stamp back tostruct tm.
|
I want to do a screenshot of a GUI window from C/C++ into the memory.
It would be really nice if it's a two dimension array of RGB values or something similar.
Im at the moment searching for a Linux based solution, but would be nice if there is a platform independent solution.
|
You could utilizexlibfor Linux:How do take a screenshot correctly with xlib?
AndGDIon Windows:MSDN - Capturing an Image
|
I cannot find in Internet any links to "official" GLU downloads or documentation. The links about GLU on opengl.org are defunct. The only GLU API documentation that I found is on MSDN about windows version of GLU. Is there such page as "official" GLU page and documentation and downloads for Linux?
|
http://www.opengl.org/sdk/docs/man2/
GLU documentation is the part of OpenGL 2 documentation. There isa special section for GLU functions.
|
When I'm going through source code I got a function pointer. So I usedctags -Rbut I didn't get the definition. It's like
```
int (*example)(struct arg1, struct arg2);
```
How can I get original function(definition)?
|
```
int (*example)(struct arg1, struct arg2);
```
The line above declares a variable namedexamplewhich is of typeint (*)(struct arg1, struct arg2). You can assign a compatible function pointer to it, for example:
```
int foo(struct arg1 a1, struct arg2 a2) {
// irrelevant
}
int main(void) {
int (*example)(s... |
I have C code that contains strinigication as below.
```
#define xstr(s) str(s)
#define str(s) #s
#define foo 4
```
Now xstr (foo) is evaluating as "4" correctly.
But str(foo) is getting evaluated as "foo". But I thought it should be evaluated as "4". Can any one please explain me how it is evaluated as "foo".
|
Because of macro expansion rules in C. Using thestr(s)you defined thefooimmediately gets placed as#foorather than evaluating the value offoo. When you wrap it withxstrit gives it a chance to actually evaluatefoobefore applying stringification.
The process looks something like this
```
str(foo)->#foo->"foo"
xstr(foo)... |
I am trying to write a function which returns the parent process name,if it isbash, then it should returnbash.
```
const std::string &getParentProcessName() {
static std::string name;
auto ppid = getppid();
#ifdef __FreeBSD__
// ?????
#else
...
#endif
name = "unknown";
return name;
}
```
|
Use thekinfo_getprocfunction
```
pid_t pid = ...;
struct kinfo_proc *proc = kinfo_getproc(pid);
if (proc) {
printf("Name %s\n", proc->ki_comm);
//ki_comm should be the program name
//see the sys/user.h header file for other relevant fields.
free(proc);
}
```
See also thelibprocstatfunc... |
I am trying to debug a PHP extension that is seg faulting using gdb but I seem to be running into some issues with debugging. When I run gdb with php on I get the following
```
#0 0x00007fff8eb6e732 in ?? ()
#1 0x00007fff5fbfe910 in ?? ()
#2 0x0000000100ebe21b in ?? ()
#3 0xffff0000ffff027f in ?? ()
#4 0x0000000... |
You need to ensure thatphpand yourphpextension is compiled with symbolic output (i.e. using the-gflag and not passed tostrip). Depending on your distribution, the distribution may have an alternate version.
However, that stack trace looks suspicious. It looks to me like something has overwritten the stack.
|
i have this while cicle and i need print only the registries where the apagado variable='\0'.
my structure is:
```
typedef struct {
char apagado;
char prop[MAXPLEN];
char mat[6];
double valor;
} veiculo_t;
```
...
sample of code:
```
{
FILE *f=fopen("veic.dat", "rb");
veiculo_t *t = malloc(sizeof(veiculo... |
Wrong use of parameters:
```
while(fread(t, sizeof(char), sizeof(*t), f))
```
Should be
```
while(fread(t, sizeof(*t), 1, f))
```
The first returns values0 ... sizeof(*t).. The second returns0 ... 1. So to prevent a partially filled structure, use the 2nd form.
```
while(fread(t, sizeof(*t), 1, f)) {
if (t->ap... |
I'm writing a basic program to learn how to use basic input/output in C, and it works just fine. The only problem I have is when it prints, there is a "%" at the end of the string on the terminal. Here's my code:
```
#include <stdio.h>
int main(int argc, char **argv) {
char name[32];
printf("Enter your nam... |
There's nothing in your code that should explain this behavior. However, it seems likely that if you are running this from a shell, that may be your shell prompt.
Add a newline to your output:
```
printf("Hello, %s\n", name);
```
This should cause the prompt to print on the next line as you probably expected.
|
I came across an unfamiliar array initialization syntax in the code ofxv6.
Original code is in syscall.s
```
static int (*syscalls[])(void) = {
[SYS_fork] sys_fork,
[SYS_exit] sys_exit,
[SYS_wait] sys_wait,
// ...
[SYS_halt] sys_halt,
};
```
I ran my sample code to confirm this
```
const char* mystrings[]... |
Designated initializers, part of C99. See for examplethe GCC documentation. The current standard reference is C11 6.7.9.
However, GCC offers a few extensions to this syntax, such as omitting the=sign, or ranges.
|
So I have this little while loop which seems to print out my text twice during one run.
So here is the code:
```
int main(void){
char cont;
int check = 1;
while(check == 1){
printf("Something");
cont = getchar();
if(cont == 'j')
check = 1;
}
}
```
Now the output of this is:
Something, now it waits f... |
You press 'j' and the 'newline', so you typed two chars and loop executes twice before starting to read next line.
|
I have appliedstrtok()in a loop in C language using this code:
```
printf("%s",line);
printf("%d %d %d\n",atoi(strtok(line," ")),atoi(strtok(NULL," ")),atoi(strtok(NULL," ")) );
```
The output is:
```
103 70 105 150
103 0 0
115 17 127 21
115 127 17
10 108 105 97
10 105 8
13 122 43 8
13 43 122
50 187 35 71
... |
In your case, the order of evaluation of parameters of printf is reverse than you think. In fact, the order of evaluation of parameters is not strictly defined in C, so you shall rearrange your code to something like:
```
printf("%d ",atoi(strtok(line," ")));
printf("%d ",atoi(strtok(NULL," ")));
printf("%d\n",atoi(s... |
If I want to return strdup from a function whose return type is char*, then what are the risks or chances of memory leak ?
```
char* fun () {
return strdup("hello");
}
int main() {
for(;;)
printf("%s\n", fun());
}
```
|
strdup()returns a pointer to newly-allocated memory that must be freed later withfree(). You'll leak memory if you don't callfree()on it — which, in your example, you don't.
|
I am writing a UART driver. I came across the two functions in the chapter 14.Linux Device Model.
```
int device_register(struct device *dev);
int driver_register(struct device_driver *drv);
```
Since UART is a char driver I have dynamically created the major number using (alloc_chrdev_region)and added the device to... |
driver_register: Adds this driver to thebus' list of drivers.
device_register:Bus' list of driversis iterated to find the driver that supports this device and then this device is added to thebus' list of devices.
|
I have an issue where one of my struct typedefs,mode_t, clashes with one in thestdlib
mode_tis already defined insys/types.h
whats best practice in this instance? to rename my struct to something else or is there some other way to resolve the clash?
|
Neverhave your own structure name or variable name that ends in_t. Regard all such names as reserved by either the compiler or the standard library.
Although technically legal by the C standard, many platforms (e.g. POSIX) explicitly forbid it.
Your best option is to rename your structure.
|
I have a problem in the following code:
```
char* temp;
temp=realloc(dish->name,(sizeof(name)+1)*sizeof(char));
if(temp == NULL){
return DISH_NULL_ARGUMENT;
}
dish->name=temp;
```
dish->nameischar*, this code works! but when in a different function I write:free(dish->name), the program is crashing!
|
What isname? Usingsizeofon something that might be a pointer is very scary.
Also, please don't scale allocations bysizeof (char), it's always equal to 1 so it just adds noise and a general sense of the author being confused.
When usingrealloc()to grow something, it's good practice to grow it by more than a single el... |
here is the smallest code that output itself. But can't grasp how this works. can somebody explain?
```
main(a){printf(a,34,a="main(a){printf(a,34,a=%c%s%c,34);}",34);}
```
|
I bet it won't work on a 64-bit platform unless its model is ILP64 (64-bitints), because it relies onintbeing big enough to contain achar*.
It declares a variableathat contains a copy of the code minus the string itself, and uses printf()'s formatting codes to output both the code and the string. Do you need more det... |
I have a situation where in the address inside the void pointer to be copied to a another pointer. Doing this without a type cast gives no warnings or errors. The pseudo code looks like
```
structA A;
void * p = &A;
structA * B = p;// Would like to conform this step
```
I don't foresee any problems with this.
But s... |
No, this is fine and 100% standard.
Avoid *can be converted to and from any other data/object pointer without problems.
Note that data/object restriction: function pointersdo notconvert to/fromvoid *.
This is the reason whyyou shouldn't cast the return value ofmalloc(), which returns avoid *.
|
I am working on a linux system. I have a multi-threaded application that hasnfile handles open on a single filef. How can I see during run-time how many file handles in my process refer ton?
|
You could check the symbolic links in/proc/self/fd/and see if there are multiple descriptors pointing to the same file.
|
If I have this code:
```
int main ()
{
char *string = "beach" ;
char newString[50];
strcpy(newString,string);
return(0);
}
```
After running it,newStringwill be "beach", right? If I wantnewStringto be "beach.jpg", how should I do this?
Thanks.
|
To stick with your code
```
int main ()
{
char *string = "beach" ;
char newString[50];
strcpy(newString,string);
strcat(newString,".jpg");
return(0);
}
```
I assume here enough space innewString.
|
Here is my structure:
```
typedef struct {
char apagado;
char prop[MAXPLEN];
char mat[6];
double valor;
} veiculo_t;
veiculo_t.apagado='\0';
```
Why can't I initialize theapagadovariable like that?
|
veiculo_tisn't a variable. It's a type. You still have to create a variable of that type:
```
veiculo_t veiculo;
veiculo.apagado='\0';
```
|
If I have two php extensions loaded and I want a class from one custom extension to inherit the class from another php extension.
Is that possible and how ?
I was trying to use:
```
zend_register_internal_class_ex(&ce, NULL , "OtherExtension\\Namespace\\OtherClass" TSRMLS_CC);
```
But I would always get error that... |
I figured it out on my own, yes you can extend from other extensions, you have to make sure that classes in other extensions are exported with PHPAPI and that the other extension is always loaded before yours.
```
extern PHPAPI zend_class_entry *class_entry_var;
```
**:EDIT if using below code then using PHPAPI is n... |
I have a variable of typeint array[10]. Is it possible to initialize only the last item of the array?
|
Yes, using designated initializers (introduced in C99), you can write code like this:
```
int array[10] = {[9] = 42};
```
which is equivalent to:
```
int array[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 42};
```
This feature is also available in some compiler as an extension, for instance,GCC.
|
This is the code I am executing:
```
scanf("%s",expr);
i=0,j=0;
while(expr[i]!='+')
{
l[j++]=expr[i++];
}
j=0;
while(expr[i]!='=')
{
r[j++]=expr[i++];
}
j=0;
while(expr[i]!='\0')
{
s[j++]=expr[i++];
}
printf("%s %d %s %d %s %d",l,strlen(l),r,strlen(r),s,strlen(s));
```
I cannot understand why t... |
Add\0at the end of each string.
```
scanf("%s",expr);
i=0,j=0;
while(expr[i]!='+')
{
l[j++]=expr[i++];
}
l[j]='\0'; //here
j=0;
while(expr[i]!='=')
{
r[j++]=expr[i++];
}
r[j]='\0'; //here
j=0;
while(expr[i]!='\0')
{
s[j++]=expr[i++];
}
s[j]='\0'; //and here
printf("%s %d %s %d %s %d",l,strlen(l),r,str... |
I am parsing some UTF-8 text but am only interested in characters in the ASCII range, i.e., I can just skip multibyte sequences.
I can easily detect the beginning of a sequence because the sign bit is set, so thecharvalue is < 0. But how can I tell how many bytes are in the sequence so I can skip over it?
I do not ... |
Just strip out all bytes which are no valid ascii, don't try to get cute and interpret bytes >127 at all. This works as long as you don't have any combining sequences with base character in ascii range. For those you would need to interpret the codepoints themselves.
|
I'm not very familiar with the source code behind the entity we know as PHP, so I don't know whether the SPL library in general and SplFixedArray in particular are implemented in C/C++. Would anyone have the information?
|
Here you´ll find a link to a "spl_fixedarray.c" file:http://git.php.net/?p=php-src.git;a=tree;f=ext/spl=> It is C
|
I would like to avoid 'floating point error in this code.
A purpose of this code is to gain 'The average of whole numbers' but the number of 'whole numbers' is limited by the input of users. Please help me.
```
#include <stdio.h>
int main(void)
{
int num=0;
int limit;
int result=0;
printf("number o... |
When you divide 2 integers, the result is also an integer.
To return a float, you need to cast one of the arguments as a float.
So your last line becomes
```
printf("average of total integer: %f \n", result/(float)limit);
```
|
C Language:If (p) is a pointer declared as follows:
int a=5, *p;
p = &a;
What does*pwill print?
|
*pwon't "print" anything; that's just an expression that de-references the pointer, and produces whateverintvalue it points at.
You can print it with:
```
printf("*p=%d\n", *p);
```
and it will print5in your program sinceppoints ata, and the value ofais5.
The%dis important, it tellsprintf()to expect anintvalue, an... |
I'm trying to read individual bytes of an int in C, but for some reason the following happens:
```
int x = -128;
//this prints 128 255
printf("%d %d\n", ((unsigned char *) (&x))[0], ((unsigned char *) (&x))[3]);
```
Should it not print 128 128 instead?
|
The representation of-128in two's complement is
```
11111111 11111111 11111111 10000000 // 4 bytes
```
Theendiannessof a system means the order in which the bytes are stored in memory. Big-endian means that most significant byte, i.e., the first byte, is stored in the smallest address and little endian means that th... |
What are equivalents for_tsystem and _wsystemin linux?
|
Justsystem. There are no wide-string (Unicode) APIs in Linux.
|
I just saw something similar to this in some code, and I was surprised that it compiles, could anyone tell me if this has a name?
```
bool value()
{
return true;
}
int main()
{
bool value(); //why does this work? What is it?
return 0;
}
```
My brain is telling me that it is some kind of making room in... |
It's a declaration of the functionvalue().
Normally we don't put it inside the function, but it's syntactically legal. Remember that functions can be defined once, but can be declared multiple times.
|
I have an assignment that requires me to create a history command, and I am stuck trying to figure out how the program would recognize that the input is a Unix command then send it to a file. If a user types junk, then it would not be sent to the history file; but if they type something likedate, that would be sent to... |
You have to "look" into the environment variable PATH, and if the first word of the command correspond to a program that's inside the PATH, or (if it begin with a "/" and the program exist), you write that to the file. Good luck!
|
In the below code why does the struct have two variable names?
```
#include <sys/resource.h>
int main (int argc, char **argv)
{
const rlim_t kStackSize = 64L * 1024L * 1024L;
struct rlimit rl; //HERE
int result = getrlimit(RLIMIT_STACK, &rl);
return 0;
}
```
|
In C, struct with its tag together is a name, unless it'stypedefed.
In C++, you can omit thestructkeyword.
|
```
int main (int argc, char *argv[])
{
FILE *in;
extern FILE *popen();
char buff[512];
char buff2[1024];
snprintf(buff2, 1024, "ifconfig eth0 | grep HWaddr | awk '{for(i=0;i<5;i++) sub(":","-",$5); print $5}'");
if(!(in = popen(buff2, "r")))
{
exit(1);
}
while(fgets(... |
Look at your use of open/close double quotes on this line:
```
snprintf(buff2, 1024, "ifconfig eth0 | grep HWaddr | awk '{for(i=0;i<5;i++) sub(":","-",$5); print $5}'");
```
You are closing the double quotes right before the :. Try escaping the double-quotes within the string with \".
|
In order to cheat the game 2048 for fun, does anyone know how to change the random implementation on Windows or Linux?
On a linux kernel, I guess that you reimplement the rand function simply like this:
```
double rand() {
return 0.0;
}
```
then rebuild your kernel.
But no idea on Windows.
I would appreciate any... |
In order to beat 2048 simply open your web browser's console while playing the game and type in:
```
Math.random = function() { return 0.0 }
```
In firefox it isTools -> Web developer -> Web console
In Chromium it isTools -> Javascript console.
P.S. I had to check if it's not yet April 1st as rebuilding kernel in ... |
I'm trying to return a pointer to a pointer from a function.
I have the following function
```
char **foo() {
const char **bar;
...
return bar;
}
```
and I get the following warning:
```
warning: return from incompatible pointer type [enabled by default]
```
what am I missing?
|
You can't jsut cast away the const qualifier like that. It points to pointers to const chars. You can however:
```
const char **foo() {
const char **bar;
...
return bar;
}
```
|
My task is to create array, In order to do that I need to input size, but I have to make sure that the input isn't negative, letter or symbol. I created function to do that, but my if doesn't work properly. If I enter negative number or character it still uses it.
Here's the function which I use:
```
void getsize(in... |
The main problem is, you compare the address of the value to 0.sizeis a pointer, so use:
```
(*size > 0)
```
instead of
```
(size > 0)
```
|
I have found the following function definition :
```
static inline __attribute__((always_inline)) int fn(const char *s)
{
return (!s || (*s == '\0'));
}
```
And I want to know the meaning ofinline __attribute__((always_inline))?
|
The often referencedgccdocumentation foralways_inlineis incomplete.
always_inlineattribute makesgcccompiler:
Ignore-fno-inline(this is what the documentation says).Ignorethe inlining limitshence inlining the function regardless. It also inlines functions withallocacalls, whichinlinekeyword never does.Not produce an ... |
Learner question. I can declare and initialize a pointer in two different way
```
int a = 10;
int *p = &a;
```
also
```
int a = 10;
int *q;
q = &a;
```
I want to know what is the difference between two and how does it work in the memory?
|
Those two are the same :
```
int *p; // declaration
p = &a; // assignment
```
and in the other you are combining the two steps together into one:
```
int *p=&a; // declaration and assignment
```
And if you have some compiler optimizations ON, the compiler might combine the two steps.
|
In order to cheat the game 2048 for fun, does anyone know how to change the random implementation on Windows or Linux?
On a linux kernel, I guess that you reimplement the rand function simply like this:
```
double rand() {
return 0.0;
}
```
then rebuild your kernel.
But no idea on Windows.
I would appreciate any... |
In order to beat 2048 simply open your web browser's console while playing the game and type in:
```
Math.random = function() { return 0.0 }
```
In firefox it isTools -> Web developer -> Web console
In Chromium it isTools -> Javascript console.
P.S. I had to check if it's not yet April 1st as rebuilding kernel in ... |
I'm trying to return a pointer to a pointer from a function.
I have the following function
```
char **foo() {
const char **bar;
...
return bar;
}
```
and I get the following warning:
```
warning: return from incompatible pointer type [enabled by default]
```
what am I missing?
|
You can't jsut cast away the const qualifier like that. It points to pointers to const chars. You can however:
```
const char **foo() {
const char **bar;
...
return bar;
}
```
|
My task is to create array, In order to do that I need to input size, but I have to make sure that the input isn't negative, letter or symbol. I created function to do that, but my if doesn't work properly. If I enter negative number or character it still uses it.
Here's the function which I use:
```
void getsize(in... |
The main problem is, you compare the address of the value to 0.sizeis a pointer, so use:
```
(*size > 0)
```
instead of
```
(size > 0)
```
|
I have found the following function definition :
```
static inline __attribute__((always_inline)) int fn(const char *s)
{
return (!s || (*s == '\0'));
}
```
And I want to know the meaning ofinline __attribute__((always_inline))?
|
The often referencedgccdocumentation foralways_inlineis incomplete.
always_inlineattribute makesgcccompiler:
Ignore-fno-inline(this is what the documentation says).Ignorethe inlining limitshence inlining the function regardless. It also inlines functions withallocacalls, whichinlinekeyword never does.Not produce an ... |
Learner question. I can declare and initialize a pointer in two different way
```
int a = 10;
int *p = &a;
```
also
```
int a = 10;
int *q;
q = &a;
```
I want to know what is the difference between two and how does it work in the memory?
|
Those two are the same :
```
int *p; // declaration
p = &a; // assignment
```
and in the other you are combining the two steps together into one:
```
int *p=&a; // declaration and assignment
```
And if you have some compiler optimizations ON, the compiler might combine the two steps.
|
I'm trying to write an audio application in C.
for now I support pulseaudio and alsa, now it's time to support jack.
I want to be able to retrieve input devices in jack in order to choose one, connect to it and record the audio from that device.
what I didn't manage to understand is how to get the list of record and... |
I haven't tested this, but theLooking up portssection of the manual has the function
```
const char ** jack_get_ports(jack_client_t *, const char *port_name_pattern,
const char *type_name_pattern, unsigned long flags);
```
If you call it withNULLpatterns and set flags toJackPortIsInput, ... |
I have created this program, it converts miles into km but answer is wrong when i compare it with my Phone's result. But in program everything is fine.
```
int main(void) {
char i;
float km, miles;
do {
printf("Enter Distance in Miles: "); scanf("%f", &miles);
km = miles * 1.906;
printf("Distance in KM... |
Your conversion factor is wrong: there are 1.609 km in 1 mile.
More precisely, 1 foot is 0.3048 m (by definition), so 5280 ft (1 mile) is (5280 * 0.3048 / 1000) = 1.609344 km.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.