question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
crypt function for data encryption (using eclipse IDE) is giving me errors in this line of myCcodecrypt("password", pwd->sp_pwdp);It says that it is undefined. I got the same error when I tried the same code in ubuntu with gcc (gcc test.c) , I guess is linker error because it worked fine in ubuntu when I tried thisgc... |
Add the library to the linker options in the project settings. In my version of Eclipse, that's:
Project -> Properties -> C/C++ Build -> Settings -> Tool Settings -> Linker -> Libraries
Addcryptto the "Libraries (-l)" panel.
|
I have gone through the available questions on Stack overflow but I did not find any relevant to my problem. I have image which contains binary data, each pixel I access as a byte but as my image binary I can release the memory using bit packing. But I don't know how to do it and I'm not finding any good sources to le... |
Not sure what references you found ... Or what the actual problem is.
You can do something like this:
```
typedef enum { ZERO, ONE, TWO, THREE } pix2;
uint8_t pack_values(pix2 p1, pix2 p2, pix2 p3, pix4 p4)
{
return (p1 << 6) | (p2 << 4) | (p3 << 2) | p4;
}
```
The above will "pack" four two-bit values into a s... |
I'm usingeclipse android IDE(bundle)
a strange thing,
I have build my android application successfully (no errors)
it includes android Apllication project and a native c code project.
I try to run the android project on my android-device
and get this error:
Description Resource Path Location Type
Andr... |
Go to Project in menu and do Clean your project which one you selecting then run your program.
|
Is there a way, as the server, to get the client's IP address as a string after receiving a message from the client withrecvfrom()? I would assume it is in thesockaddr_instruct, but I don't know how to access it. Can anyone tell me how I can do this?
|
The IP address is indeed stored in thestruct sockaddrorstruct sockaddr_inwhose address was passed torecvfrom, and (assuming the structure is named "sender") it can be converted to a string with:
```
#include <arpa/inet.h>
char* ipString = inet_ntoa(sender.sin_addr);
```
|
I coded a basic shell in C for executing basic commands like ls , pwd , ...I have a feature that can make a process run in the background instead of waiting until its done for example : ls & instead of ls (I have a list that contains the processes that run in the background now)The whole thing is that I want to know w... |
When a child process terminates,SIGCHLDsignal is sent to parent.waitpidfunction withWNOHANGflag can be used to check if a child process has terminated or is still running. Probably, you'll want to combine those both methods.
|
How can I represent an unsigned integer as Binary ?
|
To create a string representation of some integer value you can use the followingcode:
```
#include <stdlib.h>
int main(int argc, char *argv[]) {
int j;
unsigned int value = 1024+2048+4096; // some value
char mask[8*sizeof(unsigned int) + 1] = {0};
for (j = 0; j < (8*sizeof(unsigned int) + 1); j++) {
mas... |
I have a number of string values (lookup keys) that are assembled as X.Y.Z where X and Y are hardcoded strings, and Y an individual value. I am trying to write a macro TEST(Y) that gives me X.Y.Z
Example:
```
TEST(hello) -> X.hello.Z
TEST(foo) -> X.foo.Z
```
All my attempts so far have either led to non-expanded va... |
How are you trying this? Using##won't work because##is used to create individual tokens.
```
#define TEST(a) X.a.Z
```
should do the trick.
Edit: Err this will create tokens for you, not strings. @paddy's answer is what you want if you're building strings.
|
I would like to addwpa_ctrl.hon a C code, and thesource codehas the following header files:
```
#include "includes.h"
#include "common.h"
```
how do I suppose to have them? Do I need to install any package or do they suppose to be at the kernel header files or in the include path? If I need to include it manually, t... |
These files are part of the hostapd project, and internal header files that won't be installed so you can't just include them after installing the package.
You'd be probably better off just ripping out the parts from wpa_ctrl.h you need. Depending on what you need it might be even better to use e.g. the DBus interfac... |
Can anyone tell me why this simple Csystemcall of a shellhello worldcommand is not working:
MWE:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main( int argc, char *argv[] )
{
char *str;
str = strdup ( "hello" );
printf ( "echo %s\n", str );
system ( ( "echo %s\n", str ) );
return ... |
This doesn't do what you think it does:
```
system ( ( "echo %s\n", str ) );
```
Thecomma operatorsimply returns the second value,str, which is"hello". Therefore your program will not try to runecho hellobut justhello.
You'll want to usesprintfto write the entire command into a buffer, then execute that.
|
I am trying to figure out how to use struct but this code gives me a lot of errors.
```
#include <stdio.h>
int main(void)
{
struct date
{
int today = 6;
int tomorrow = 7;
int threeDays = 8;
};
struct date date;
printf("%d", date.today);
return 0;
}
... |
```
struct date
{
int today = 6;
int tomorrow = 7;
int threeDays = 8;
};
struct date date;
```
You cannot assign a default value to a structure type.
What you can do is to initialize an object of a structure type with the correct values:
```
struct date
{
int today;
int tomorro... |
Is there a function in c that checks whether a file is a block device or charachter device?
Thanks!
|
You're probably looking forlstat, if you're under linux:
http://linux.die.net/man/2/lstat
You should have access to the macrosS_ISCHRandS_ISBLK.
|
Say you have a struct that looks like this:
```
struct Point {
int x, y;
};
```
Now if I wanted to have a struct variable of type Point, I could do this:
```
struct Point p1 = {5, 5};
```
This works just fine. However, I have seen that you can also create struct variables like this:
```
struct Point {
int... |
It only works for initialization:
```
Point p1 = {5, 5}; // Ok
```
while it doesn't for declaration + assignment:
```
Point p2;
p2 = {5, 5}; // Error
```
|
After I open a database file withsqlite3_open()and before I close it withsqlite3_close(), does SQLite provide any mechanism to handle changes to the file path of the database file?
My experiment shows that the connection to the file is, by default, not maintained if I rename/move the file in Unix. After renaming/movi... |
There is no such mechanism.
You must not move the database file, or reopen the database afterwards.
|
Right now, I call the jump instruction with inline assembly in c as follows:
```
int register eax asm("eax") = addr; // addr is a memory address
asm("jmp *%eax");
```
I want to do it without having to set any other register values (e.g. I want to do is something like this):
```
asm("jmp *(addr)");
```
What is the ... |
"Assembler Instructions with C Expression Operands"
```
asm volatile("jmp *%0" : : "r" (addr));
```
|
I was practicing converting C code into MIPS assembly language, and am having trouble understanding the usage ofmoveandliin variable assignment.
For example, to implement the following C line in MIPS:
```
int x = 0;
```
If I understand it correctly (I highly doubt this, though), it looks like both of these work in ... |
Themoveinstruction copies a value from one register to another. Theliinstruction loads a specific numeric value into that register.
For thespecificcase of zero, you can use either the constant zero or the zero register to get that:
```
move $s0, $zero
li $s0, 0
```
There's no register that generates a value other... |
I am looking at the source for the android shellrebootcommand.
```
int reboot_main(int argc, char *argv[])
```
What I am not clear about is if this is a standalone binary, who calls reboot_main() ?In a standard glibc linked binary, I was expecting to find a "main()" as the entry point for the program.
What am I mis... |
They are all compiled into one overall executable, withmaininhttps://android.googlesource.com/platform/system/core.git/+/android-4.2.2_r1/toolbox/toolbox.c
Then, based on the actual program name invoked (usuallyargv[0]) it calls the appropriate method.
The commands are part of the build via the
```
#define TOOL(nam... |
I'm heaving a problem on printing a hash generated with OpenSSL, code (using OpenSSL):
```
char *computeHash(char *msg){
static char hs[20];
SHA1(msg, strlen(msg), hs);
return hs;
}
int main(){
char *text;
char *hash;
int i;
text = "test";
hash = computeHash(text);
for(i=0;i<20... |
The%02xformat string is for an integer. But you are printing a character. Also,hashis achar *pointer, you probably want anunsigned char *. How about:
```
unsigned char *hash_ptr = (unsigned char *) hash;
for(i=0;i<20;i++){
printf("%02x", (int) hash_ptr[i]);
}
```
|
I write a new program that compares 2 two digit unsigned integer. Compares by hamming distances. But my algorithm doesn't work perfectly. Can yo tell me what is wrong with this code :( THANKS A LOT!!
this is my counting method;
```
int countHammDist(unsigned int n, unsigned int m)
{
int i=0;
unsigned int count = 0 ;... |
Put parantheses around n&1 and m&1.
```
if ((n&1) != (m&1))
```
http://ideone.com/F7Kyzg
This is because != is before &:http://www.swansontec.com/sopc.html
|
I've created and mounted an ext4 file system using:
```
sudo mkfs.ext4 /dev/sdb
sudo mkdir /ext4_filesystem
sudo mount -t ext4 /dev/sdb /ext4_filesystem
```
Now I'm trying to create a file in this file system using:
```
sudo ./mycode "~/ext4_filesystem/2.txt"
```
where the argument of "mycode" is the location of ... |
The "~" should not be there. You mounted/ext4_filesystem, not~/ext4_filesystem.
|
Here's my ramdomize code:
```
int monstername;
monstername = rand() % 3;
```
but I want 0 with 70% of output 1 with 20% 2 with 10% how I can do this with C?
|
```
int monstername;
int random_var = rand() % 10;
if(random_var < 7) {
// 0-70%
monstername = 0;
}
else if(random_var < 9) {
// 70-90% here
monstername = 1;
}
else {
// 90-100% here
monstername = 2;
}
```
|
Is there a way, as the server, to get the client's IP address as a string after receiving a message from the client withrecvfrom()? I would assume it is in thesockaddr_instruct, but I don't know how to access it. Can anyone tell me how I can do this?
|
The IP address is indeed stored in thestruct sockaddrorstruct sockaddr_inwhose address was passed torecvfrom, and (assuming the structure is named "sender") it can be converted to a string with:
```
#include <arpa/inet.h>
char* ipString = inet_ntoa(sender.sin_addr);
```
|
I coded a basic shell in C for executing basic commands like ls , pwd , ...I have a feature that can make a process run in the background instead of waiting until its done for example : ls & instead of ls (I have a list that contains the processes that run in the background now)The whole thing is that I want to know w... |
When a child process terminates,SIGCHLDsignal is sent to parent.waitpidfunction withWNOHANGflag can be used to check if a child process has terminated or is still running. Probably, you'll want to combine those both methods.
|
How can I represent an unsigned integer as Binary ?
|
To create a string representation of some integer value you can use the followingcode:
```
#include <stdlib.h>
int main(int argc, char *argv[]) {
int j;
unsigned int value = 1024+2048+4096; // some value
char mask[8*sizeof(unsigned int) + 1] = {0};
for (j = 0; j < (8*sizeof(unsigned int) + 1); j++) {
mas... |
I have a number of string values (lookup keys) that are assembled as X.Y.Z where X and Y are hardcoded strings, and Y an individual value. I am trying to write a macro TEST(Y) that gives me X.Y.Z
Example:
```
TEST(hello) -> X.hello.Z
TEST(foo) -> X.foo.Z
```
All my attempts so far have either led to non-expanded va... |
How are you trying this? Using##won't work because##is used to create individual tokens.
```
#define TEST(a) X.a.Z
```
should do the trick.
Edit: Err this will create tokens for you, not strings. @paddy's answer is what you want if you're building strings.
|
I would like to addwpa_ctrl.hon a C code, and thesource codehas the following header files:
```
#include "includes.h"
#include "common.h"
```
how do I suppose to have them? Do I need to install any package or do they suppose to be at the kernel header files or in the include path? If I need to include it manually, t... |
These files are part of the hostapd project, and internal header files that won't be installed so you can't just include them after installing the package.
You'd be probably better off just ripping out the parts from wpa_ctrl.h you need. Depending on what you need it might be even better to use e.g. the DBus interfac... |
Can anyone tell me why this simple Csystemcall of a shellhello worldcommand is not working:
MWE:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main( int argc, char *argv[] )
{
char *str;
str = strdup ( "hello" );
printf ( "echo %s\n", str );
system ( ( "echo %s\n", str ) );
return ... |
This doesn't do what you think it does:
```
system ( ( "echo %s\n", str ) );
```
Thecomma operatorsimply returns the second value,str, which is"hello". Therefore your program will not try to runecho hellobut justhello.
You'll want to usesprintfto write the entire command into a buffer, then execute that.
|
Can anyone tell me why this simple Csystemcall of a shellhello worldcommand is not working:
MWE:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main( int argc, char *argv[] )
{
char *str;
str = strdup ( "hello" );
printf ( "echo %s\n", str );
system ( ( "echo %s\n", str ) );
return ... |
This doesn't do what you think it does:
```
system ( ( "echo %s\n", str ) );
```
Thecomma operatorsimply returns the second value,str, which is"hello". Therefore your program will not try to runecho hellobut justhello.
You'll want to usesprintfto write the entire command into a buffer, then execute that.
|
I am trying to figure out how to use struct but this code gives me a lot of errors.
```
#include <stdio.h>
int main(void)
{
struct date
{
int today = 6;
int tomorrow = 7;
int threeDays = 8;
};
struct date date;
printf("%d", date.today);
return 0;
}
... |
```
struct date
{
int today = 6;
int tomorrow = 7;
int threeDays = 8;
};
struct date date;
```
You cannot assign a default value to a structure type.
What you can do is to initialize an object of a structure type with the correct values:
```
struct date
{
int today;
int tomorro... |
Is there a function in c that checks whether a file is a block device or charachter device?
Thanks!
|
You're probably looking forlstat, if you're under linux:
http://linux.die.net/man/2/lstat
You should have access to the macrosS_ISCHRandS_ISBLK.
|
Say you have a struct that looks like this:
```
struct Point {
int x, y;
};
```
Now if I wanted to have a struct variable of type Point, I could do this:
```
struct Point p1 = {5, 5};
```
This works just fine. However, I have seen that you can also create struct variables like this:
```
struct Point {
int... |
It only works for initialization:
```
Point p1 = {5, 5}; // Ok
```
while it doesn't for declaration + assignment:
```
Point p2;
p2 = {5, 5}; // Error
```
|
After I open a database file withsqlite3_open()and before I close it withsqlite3_close(), does SQLite provide any mechanism to handle changes to the file path of the database file?
My experiment shows that the connection to the file is, by default, not maintained if I rename/move the file in Unix. After renaming/movi... |
There is no such mechanism.
You must not move the database file, or reopen the database afterwards.
|
I want to do some programming for Xbee, for this i have found a nice library namely the: libXbee. This library can be found here:Link. But i can't find a way to use the library with MinGw and eclipse. Is there anyone how has used the libxbee library that can give me some pointers on how to do this? Or what is a good a... |
Now that's unfair - I offered you lots of pointers as to where to start with porting it, it already compiles and runs on Windows (using Microsoft's toolchain) and I even said I might be able to have a look at itfor youthis weekend!...
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do... |
Of course, given how pervasive use of these hashes is. For example, OpenSSL has them; seehereandherefor basic documentation.
There are also standalone implementations; eghereis what I use in mydigestpackage for R.
|
Hi does anyone know how to get the process ID for the binary that is being instrumented by PIN? So for example if I have something like:
```
pin -t MyTool -- somebinary
```
How do I get the process ID for 'somebinary' inside the PINTool that I'm trying to write. I checked the documentation but there doesn't seem to ... |
I think you can directly use getpid()? This is how I do when making Pin tools.
http://man7.org/linux/man-pages/man2/getpid.2.html
Pin also provides process related APIs
http://software.intel.com/sites/landingpage/pintool/docs/62732/Pin/html/group__PIN__PROCESS__API.html
|
I am new to matlab. I want to return 0, if the value ofeisNaN. Following is my code:
```
if(e!='NaN')
fprintf(1,'The final coefficiant is: %f \n',e);
else
return 0;
end
```
It's showing me
Unexpected MATLAB operator.
Can anybody tell me why? How should I write it?
|
Also != is not a valid MATLAB operator. That's your error.
Use~=
Nothing is ever, ever, ever == NaN.
Not even NaN. Useisnan
```
function out = my_fun(e)
if ~isnan(e)
fprintf('The final coefficiant is: %f \n',e);
out = 1; % or whatever
else
out = 0;
end
```
|
I have a variable (unsigned int)part_1.
If I do this:NSLog(@"%u %08x", part_1, part_1);(print unsigned value, and hex value) it outputs:
2063597568 7b000000
(only first two will have values).
I want to convert this to
0000007b
So i've tried doingunsigned int part_1b = part_1 >> 6(and lots of variations)
But th... |
You want to shift by 6*4 = 24 bits, not just 6 bits. Each '0' in the hex printf represents 4 bits.
```
unsigned int part_1b = part_1 >> 24;
^^
```
|
So given thiscstructure:
```
typedef struct {
int* arr1;
int* arr2;
} myStruct;
```
This answerdescribed using a singlemallocto allocate amyStructand it's arrays at the same time:
```
myStruct* p = malloc(sizeof(*p) + 10 * sizeof(*p->arr1) + 10 * num * sizeof(*p->arr2);
if(p != NULL) {
p->arr1 = (int*)... |
You can allocate a block of memory usingnewwith an array ofchar, then useplacement newto call the constructor on that block of memory.
|
```
ALTER PROCEDURE dbo.spReturnLastRowNoteID
(@noteid int OUTPUT)
AS
SET NOCOUNT ON
SELECT @noteid = NoteID
FROM NoteTable
WHERE NoteID = IDENT_CURRENT('NoteTable')
RETURN @noteid`
```
I don't think there is a problem in my sp and code but I'm not sure why i'm getting the error:
```
using (SqlConnection c... |
Try setting the parameters direction to Output.
```
noteid.Direction = ParameterDirection.Output;
```
|
I'm trying to split a string at spaces and tabs.
```
char * token = strtok(input, " \t");
```
works only for spaces. What am I doing wrong?
|
Here is an example that illustrates that strtok() will work on tabs or spaces.
The key is to pass in NULL on the all but the first call to strtok().
```
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char buffer[1024];
int rv = sprintf(buffer, "a string\ttokenize.");
char *token... |
Simple question, I hope
I have a c program that does a lot of math. It requires a few input floats and then returns a few floats. I would like this code to be incorporated into a bash script that runs it at the right time and passes it the right value, and then reads the result.
What is the simplest and easiest wa... |
You can pass command line arguments to your C program, througharguments tomain. In the easiest case, your program returns a single number (result) and you can capture that result back in your bash script:
```
#!/bin/sh
...
RESULT=$(mycprogram arg1 arg2)
...
```
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do... |
Of course, given how pervasive use of these hashes is. For example, OpenSSL has them; seehereandherefor basic documentation.
There are also standalone implementations; eghereis what I use in mydigestpackage for R.
|
Is there a function in thecmathlibrary which given 3 numbersx,yandzreturnsx*y+z?
|
fmawhich stands for Fused Multiply Add was introduced in C99 andC++11:
```
#include <cassert>
#include <cmath>
int main() {
assert(std::fabs(std::fma(2.0, 3.0, 4.0) - (2.0 * 3.0 + 4.0)) < 0.001);
}
```
Probable rationales:
IEEE 754-2008seems to have added support for the operation, requiring that it be done wi... |
I found a puzzling array when I tried to put parenthesis to emphasize the declaration of array of pointers as in(int *) ptr[N];.
The GCC C compiler says:
error: ptr undeclared (first use in this function).
Can anyone explain the origin of the error please?
|
It's very simple: The variableptrhave not been declared. And no,(int *) ptr[N];isnota declaration, it's a typecast of an array subscript expression.
If you want an array of pointers, you should do
```
int *ptr[N];
```
|
For a class project, I have to read a file and store it's contents in an array to be sorted. The one nice thing is that the file will be piped in through standard input, but the only problem is that I can not assume that the file is not growing: I have to check for EOF. How do I do this using malloc() and realloc()?
|
Here's one way: Use malloc to allocate an array of chars with a reasonable default size like 4096. Start reading characters from the standard input into the array until you get the EOF. Whenever the array fills up, callreallocto double the size of the array.
|
I recently came across a C code (working by the way) where I found
```
freq_xtal = ((622.08E6 * vcxo_reg_val->hiv * vcxo_reg_val->n1)/(temp_rfreq));
```
From my intuition it seems that622.08E6should mean622.08 x 10^6. Is this assumption correct?
I tried googling for a similar example where E notation is used in a C... |
Yes, that is correct. It works just like an old-school scientific calculator.
In this case, it looks like you're dealing with a 622.08MHz signal and a VCOX on a PLL?
|
I don't understand the below error message when I compile this code. I couldn't find out what wrong with it.
```
Description Resource Path Location
Type expected ‘)’ before ‘SCNu64’.
#include <inttypes.h>
int calc_rate(uint64_t *rate, char val[], char mult[]) {
int rc = sscanf(val, "%" SCNu64 "%2s", rate, mu... |
If you have both<inttypes.h>and<stdio.h>included, then the code fragment shown compiles cleanly. (You can't callsscanf()legally unless there's a prototype in scope.) That means the problem is in the code prior to what you are showing. Or it means that your compiler doesn't provide support for exactly 64-bit types, whi... |
I'm developing a c application on an embedded processor with a gcc-based toolchain. In my application I need to place a flag at a specific memory location. I need help with the linker command file syntax to accomplish this.
|
In your C file write something like:
```
static int flag __attribute__ ((section (".flag"))) __attribute__ ((__used__)) = 6;
```
In your custom linker script, add .flag to the desired section:
```
_flag_start = 0x00001234;
.flag _flag_start :
{
KEEP(*(.flag)) ;
}
```
Be sure to add this on the correct place, as... |
I'm trying to do a simple do while loop where any letter other than 'y' or 'n' is invalid and the loop is repeated. Does anyone know why this loop always evaluates to false? Even when a valid character is entered?
```
char user_response[2];
do {
printf("\nDo you want to process another range (y or n): ");
sc... |
You should change || to &&.
|
I've been using theread(2)andwrite(2)functions to read and write to a file given a file descriptor.
Is there any function like this that allows you to put an offset into the file for read/write?
|
There arepread/pwritefunctions that accept file offset:
```
ssize_t pread(int fd, void *buf, size_t count, off_t offset);
ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset);
```
|
I found a puzzling array when I tried to put parenthesis to emphasize the declaration of array of pointers as in(int *) ptr[N];.
The GCC C compiler says:
error: ptr undeclared (first use in this function).
Can anyone explain the origin of the error please?
|
It's very simple: The variableptrhave not been declared. And no,(int *) ptr[N];isnota declaration, it's a typecast of an array subscript expression.
If you want an array of pointers, you should do
```
int *ptr[N];
```
|
For a class project, I have to read a file and store it's contents in an array to be sorted. The one nice thing is that the file will be piped in through standard input, but the only problem is that I can not assume that the file is not growing: I have to check for EOF. How do I do this using malloc() and realloc()?
|
Here's one way: Use malloc to allocate an array of chars with a reasonable default size like 4096. Start reading characters from the standard input into the array until you get the EOF. Whenever the array fills up, callreallocto double the size of the array.
|
I recently came across a C code (working by the way) where I found
```
freq_xtal = ((622.08E6 * vcxo_reg_val->hiv * vcxo_reg_val->n1)/(temp_rfreq));
```
From my intuition it seems that622.08E6should mean622.08 x 10^6. Is this assumption correct?
I tried googling for a similar example where E notation is used in a C... |
Yes, that is correct. It works just like an old-school scientific calculator.
In this case, it looks like you're dealing with a 622.08MHz signal and a VCOX on a PLL?
|
I don't understand the below error message when I compile this code. I couldn't find out what wrong with it.
```
Description Resource Path Location
Type expected ‘)’ before ‘SCNu64’.
#include <inttypes.h>
int calc_rate(uint64_t *rate, char val[], char mult[]) {
int rc = sscanf(val, "%" SCNu64 "%2s", rate, mu... |
If you have both<inttypes.h>and<stdio.h>included, then the code fragment shown compiles cleanly. (You can't callsscanf()legally unless there's a prototype in scope.) That means the problem is in the code prior to what you are showing. Or it means that your compiler doesn't provide support for exactly 64-bit types, whi... |
I'm developing a c application on an embedded processor with a gcc-based toolchain. In my application I need to place a flag at a specific memory location. I need help with the linker command file syntax to accomplish this.
|
In your C file write something like:
```
static int flag __attribute__ ((section (".flag"))) __attribute__ ((__used__)) = 6;
```
In your custom linker script, add .flag to the desired section:
```
_flag_start = 0x00001234;
.flag _flag_start :
{
KEEP(*(.flag)) ;
}
```
Be sure to add this on the correct place, as... |
I'm trying to do a simple do while loop where any letter other than 'y' or 'n' is invalid and the loop is repeated. Does anyone know why this loop always evaluates to false? Even when a valid character is entered?
```
char user_response[2];
do {
printf("\nDo you want to process another range (y or n): ");
sc... |
You should change || to &&.
|
I've been using theread(2)andwrite(2)functions to read and write to a file given a file descriptor.
Is there any function like this that allows you to put an offset into the file for read/write?
|
There arepread/pwritefunctions that accept file offset:
```
ssize_t pread(int fd, void *buf, size_t count, off_t offset);
ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset);
```
|
I am trying to build Com0Com with the new Visual Studio 2013 and DDK. Microsoft has changed the way drivers are built quite a bit, but I have been able to create a driver project (KMDF) and add the Com0Com source files to the project. (The build instructions that come with Com0Com don't work with the new way Microsof... |
With the help of the suggestion of @Hans Passant I was able to figure it out:
Put the following as a Pre-Build Event under Build Events:
mc.exe c0clog.mc
|
Is it possible to fork a process and have the parent process tell the forked process to call a function and return its results to the parent? If so, how can we accomplish this? I'm not sure if the best way to perform the inter-process communication is through pipes or sockets (or some other structure). I'm only intere... |
If you have a parent-child relationship, I think that unnamed pipes (AKA "pipes") are better. Otherwise, you can use local sockets or FIFOs (AKA "named pipes").
You can make the parent send an integer to the child. The child, based on the integer received, runs a certain function and sends back the result to the pare... |
```
unsigned short int uwVal1=-10;short int wVal2=-10;
if(uwVal1==wVal2)
printf("Something");
```
What i know as per my knowledge is that whenever unsigned type is compared with signed type ....signed will convert it to unsigned for the moment. So by that logic...above code should print "Something".
if i do like thi... |
Yes, the logic is different from what you think.
The logic is explained fully by STL's video onThe Usual Arithmetic Conversions.
(In the comparison,both sidesare promoted toint, so you're comparing 65526 and -10.)
|
I need to use GMPs mpf_t/mpz_t as keys in a hashtable.
Is there any efficient way to access the raw bytes of the number representation so I can run a hash function over them?
I already read the documentation but I don't really feel smarter now. ;)
Thanks!
Regards,
Ethon
|
Out of curiosity, why use hashing when you can sort by value? Comparison is very quick, as it compares the bytes / limbs from MSB to LSB, returning a result as soon as they differ.
You can access the raw data using the platform-dependentmp_limb_ttype. Bothmpz_tandmpf_thave anmp_limb_tvector stored at the address spec... |
In a macro declaration like:
```
#define WAIT_SPI2_TRANSMISSON_END() {while ((SPI2_SR & SPI_SR_TXCTR_MASK) != 0) {\
if( SPI2_SR & SPI_SR_RFDF_MASK ) {\
(void)SPI2_POPR;\
SPI2_SR |= SPI_SR_RFDF_MASK ;\
... |
It's a line continuation character.
There should be nothing else after it (aside from an end of line character), including white space.
It's particularly useful for macros as it adds clarity.
(Very, very occasionally - especially in old code - you'll see thetrigraph sequence??/in place of\. These days though it's m... |
I have make two librarieslibsa.aandlibsb.a.
The functionfuncainlibsa.aandfuncbinlibsb.awhich callsfunca.
In the main function, I only callfuncb. The compiler display that "... undefined reference to `funca'". The compiler command like "gcc main.c -o main -lsa -lsb".
The problem is resolved when I add afuncain the ma... |
Change the order:gcc main.c -o main -lsb -lsa
|
I'm working on a cryptographic exercise, and I'm trying to calculate (2n-1)mod p where p is a prime number
What would be the best approach to do this? I'm working with C so 2n-1 becomes too large to hold when n is large
I came across the equation (a*b)modp=(a(bmodp))modp, but I'm not sure this applies in this case, ... |
A couple tips to help you come up with a better way:
Don't use (a*b)modp=(a(bmodp))modp to compute 2n-1 mod p, use it to compute 2nmod p and then subtract afterward.Fermat's little theoremcan be useful here. That way, the exponent you actually have to deal with won't exceed p.
|
For example
```
/*
* This C-like algorithm is implemented in
* hardware as a single, atomic CAS instruction.
*/
int
CAS(int* ptr, int old, int new)
{
int tmp = *ptr;
if (*ptr == old)
*ptr = new;
return tmp;
}
```
This clearly resembles a programing language so when they say it's implemented in h... |
1) Exactly. They are using C syntax to explain the result of the hardware operation. They are further stating that it acts as a single atomic operation, which means it can't be interrupted part way through by another thread.
2) I don't have the context of the statement, but that would be my assumption (that there is ... |
I'm using Anjuta and gdb on Fedora 20 and created a C Makefile project. The code looks like this:
```
#include <stdio.h>
int main (void)
{
° printf ("1");
° printf ("2");
° printf ("3");
return (0);
}
```
° means I set a breakpoint at that position.
Now when I debug the code, there's no output while the... |
By default, stdout is line buffered when writing to a terminal, fully buffered when writing to any other type of stream. Since you're not printing any newlines, the output is being buffered. You can change the buffering mode withsetbuf(), end each string with newline, or callfflush()when you want printing to take plac... |
I need maximum performances using GMP and I wonder whether there is a better way to compute the absolute value of the difference of two numbers.
Currently I use:
```
mpz_sub(x, a, b);
mpz_abs(x, x);
```
Is there a most efficient way to do that ?
|
Your code should already be close to optimal. When the source and destination are the same,mpz_abstakes constant time: it does not read the big number and only performs a trivial operation on the sign.
|
```
unsigned short int uwVal1=-10;short int wVal2=-10;
if(uwVal1==wVal2)
printf("Something");
```
What i know as per my knowledge is that whenever unsigned type is compared with signed type ....signed will convert it to unsigned for the moment. So by that logic...above code should print "Something".
if i do like thi... |
Yes, the logic is different from what you think.
The logic is explained fully by STL's video onThe Usual Arithmetic Conversions.
(In the comparison,both sidesare promoted toint, so you're comparing 65526 and -10.)
|
I need to use GMPs mpf_t/mpz_t as keys in a hashtable.
Is there any efficient way to access the raw bytes of the number representation so I can run a hash function over them?
I already read the documentation but I don't really feel smarter now. ;)
Thanks!
Regards,
Ethon
|
Out of curiosity, why use hashing when you can sort by value? Comparison is very quick, as it compares the bytes / limbs from MSB to LSB, returning a result as soon as they differ.
You can access the raw data using the platform-dependentmp_limb_ttype. Bothmpz_tandmpf_thave anmp_limb_tvector stored at the address spec... |
In a macro declaration like:
```
#define WAIT_SPI2_TRANSMISSON_END() {while ((SPI2_SR & SPI_SR_TXCTR_MASK) != 0) {\
if( SPI2_SR & SPI_SR_RFDF_MASK ) {\
(void)SPI2_POPR;\
SPI2_SR |= SPI_SR_RFDF_MASK ;\
... |
It's a line continuation character.
There should be nothing else after it (aside from an end of line character), including white space.
It's particularly useful for macros as it adds clarity.
(Very, very occasionally - especially in old code - you'll see thetrigraph sequence??/in place of\. These days though it's m... |
I have make two librarieslibsa.aandlibsb.a.
The functionfuncainlibsa.aandfuncbinlibsb.awhich callsfunca.
In the main function, I only callfuncb. The compiler display that "... undefined reference to `funca'". The compiler command like "gcc main.c -o main -lsa -lsb".
The problem is resolved when I add afuncain the ma... |
Change the order:gcc main.c -o main -lsb -lsa
|
I'm working on a cryptographic exercise, and I'm trying to calculate (2n-1)mod p where p is a prime number
What would be the best approach to do this? I'm working with C so 2n-1 becomes too large to hold when n is large
I came across the equation (a*b)modp=(a(bmodp))modp, but I'm not sure this applies in this case, ... |
A couple tips to help you come up with a better way:
Don't use (a*b)modp=(a(bmodp))modp to compute 2n-1 mod p, use it to compute 2nmod p and then subtract afterward.Fermat's little theoremcan be useful here. That way, the exponent you actually have to deal with won't exceed p.
|
For example
```
/*
* This C-like algorithm is implemented in
* hardware as a single, atomic CAS instruction.
*/
int
CAS(int* ptr, int old, int new)
{
int tmp = *ptr;
if (*ptr == old)
*ptr = new;
return tmp;
}
```
This clearly resembles a programing language so when they say it's implemented in h... |
1) Exactly. They are using C syntax to explain the result of the hardware operation. They are further stating that it acts as a single atomic operation, which means it can't be interrupted part way through by another thread.
2) I don't have the context of the statement, but that would be my assumption (that there is ... |
```
while((count++<n) && *s1++=*s2++);
*s1='\0';
```
i ran this piece of code and got an errorlvalue required as left operand of assignment in c
i was able to correct it
```
while((count++<n) && (*s1++=*s2++));
*s1='\0';
```
this works fine but i have no idea why. i read other threads in stack overflow saying ... |
The reason the first piece of code doesn't compile is&&operator has higher precedence in C than=.
So the compiler reads this as((count++<n) && *s1++) = *s2++, or more generally(A && B) = C.
|
I am Trying to use kqueue for doing an event oriented server in c when i compile my code it give me this error
fatal error: sys/event.h: No such file or directory
according to a tutorial that I am following to create the kqueue events that file have to be include I am new to events programming in C
|
kqueueis only present in BSD (FreeBSD / OpenBSD) and Darwin (Mac OS X / iOS) kernels. It does not exist in the Linux kernel.
The closest equivalents available on Linux areepollfor asynchronous I/O, andinotifyfor file system watches.
|
What does the following piece of code mean?
```
int* pointer = malloc (sizeof(int) + 3);
pointer++;
```
The allocated piece of memory can't be broken down into chunks ofsizeof(int). So what happens when pointer is asked to jump to the next "block"? Is it defined?
|
The code is valid but maybe unusual without more context.
Line 1: Themallocallocates 3 bytes larger than the size of anint. This is valid.
Line 2: Thepointer++is valid. It's just an address.
Further references topointer(e.g. addition or subtraction or comparison) are valid. Dereferences (i.e.*pointer) will resul... |
This question already has answers here:Segmentation fault on large array sizes(7 answers)Closed9 years ago.
I get a SIGSEGV when my code reach a matrix declaration and i do not get much information about it. This is my code :
```
void mascaraLaPlace(unsigned char Img[1200][1200][3],int Rx,int Ry){
int x,y,a,b,c,d;... |
Depending on the values of Rx and Ry, your array may simply be too large for the stack. If they are both 2000, for example, that's about 12 megabytes, far more than most OSs reserve for the stack by default.
|
If you want a dynamically allocated array ofint size, there two ways you can get that in C:
```
int* array = new int [size]; //method 1
int* array2 = malloc (sizeof(int) * size); //method 2
```
When should you use each method?
|
If you're in C, the second one.
If you're in C++, usestd::vector<int>if you can; otherwise use the first one (rarely needed).
|
here is the snippet from in question from my code. a is for the array and c represents the counter.
The code knows when i gained, lost, or stayed the same so it has the right value. Its just that it always displays 0 zero pounds as how much i lost or gained...
is there something wrong with passing the %i in the print... |
The integer token in the printf string is%d.
So, try this:
```
printf("You gained gained %d pounds!\n",a[*c]-a[*c-1]);
```
|
I'm building a C program using MPI, simulating some traffic lights. I need for each process to wait for a few seconds then send a message to the other traffic light (process) to change. If I use Sleep(), the program crashes. Is there a safe way to make a process sleep for a given number of seconds?
|
You can simulate your own sleep() function by usingMPI_WTIME()and manually waiting for the amount of time you need. Depending on how you're executing (number of cores, nodes, etc.) this might not have any performance hit and gives you the added benefit of being able to do something else while you're waiting for the ne... |
the codes is:
```
#define O_ACCMODE 00000003
#define ACC_MODE(x) ("\000\004\002\006"[(x)&O_ACCMODE])
```
How to understand it?Thank you.
|
"\000\004\002\006"defines array of 4 bytes/chars, we can replace it with:
char array[4] = {0, 4, 2, 6};
x&3 means - get only far right 2 bits in integer, basically it is equivalent ofx%4
so, this macro do:array[ x % 4 ]- takes proper value based on index
|
```
while((count++<n) && *s1++=*s2++);
*s1='\0';
```
i ran this piece of code and got an errorlvalue required as left operand of assignment in c
i was able to correct it
```
while((count++<n) && (*s1++=*s2++));
*s1='\0';
```
this works fine but i have no idea why. i read other threads in stack overflow saying ... |
The reason the first piece of code doesn't compile is&&operator has higher precedence in C than=.
So the compiler reads this as((count++<n) && *s1++) = *s2++, or more generally(A && B) = C.
|
I thought array and pointer are basically the same thing, until I run this program:
```
int main() {
int* a = new int(19);
int b[1];
b[0] = 19;
printf("*a: %d\n a: %p\n &a:%p\n", *a, a, &a);
printf("*b: %d\n b: %p\n &b:%p\n", *b, b, &b);
delete a;
}
```
output is:
```
*a: 19
a: 0x7f94524000e0
&a:0x7f... |
Well,bis an array. Under the slightest excuse it will decay into a pointer to the first element ofb. Note, however, that the expressionband&barenotequivalent:bdecays into a pointer the first element, i.e., it is of typeint*while&bis a pointer to the array, i.e., it is of typeint(*)[1].
|
I am running a process in my c program. I need to give parameter from the user to this process before it starts running.How can i do it?
This is my code:
```
#include<stdio.h>
#include<stdlib.h>
main()
{
char inp[10];
printf("\nInput the interface\n");
scanf("%s",inp);
system("ifconfig [interface from user(inp)]"); ... |
You do e.g.
```
char buffer[256];
snprintf(buffer, sizeof(buffer), "ifconfig %s", inp);
system(buffer);
```
If you're on Windows, use_snprintfinstead.
|
I am trying to switch from Ruby FFI to Fiddle, which is now part of Ruby std lib.
It is pretty undocumented though, and I am having a hard time in figuring out how to deal with arrays and pointers. In particular, how can I write a Fiddle interface to a C function like this:
```
void my_func(double *, size_t len)
```... |
you mean build an c array and this array`s pointer in ruby?
you can try like this:
```
free = Fiddle::Function.new(Fiddle::RUBY_FREE, [TYPE_VOIDP], TYPE_VOID)
p = Pointer.malloc(SIZEOF_DOUBLE*len, free)
```
and call like this:
```
my_func(p,len)
```
ruby GC will call the free function when this memory block will ... |
I have to extract a matrix from a file through C and calculate the determinant of it. To do this for any matrix up to a 3x3 I'm sure i'll need to know the dimensions of the matrix but I'm pretty new to programming so I don't know what options I have.
If I have a .dat file with an unspecified matrix in it what can i d... |
well what you can do is put them in array and since it is square matrix
number of rows=number of columns
find the square root of the number of elements
access is through M[i*d+j]
d is the dimension of the matrix r=c=d;
tip use dynamic arrays i.e. pointers
|
I need to get PID of foreground app programatically(in C or Obj C) in OS X.
How to solve the following problem?
|
This should do it:
```
pid_t pid=NSWorkspace.sharedWorkspace.frontmostApplication.processIdentifier;
```
|
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int n, i;
srand(time(NULL));
for(i = 1; i <= 19; i++)
printf("%d \n", rand() * 21 / RAND_MAX);
return 0;
}
```
The code works. Sort of. It displays in console 20 "random" numbers between 1-20. Like 1 19 6 8 18 6 8 et... |
What about that:
```
int biggest = 0;
for(i = 1;i < 20; i++){
int num = rand() * 21 / RAND_MAX;
if (num > biggest){
biggest = num;
}
printf("%d \n", num);
}
printf("Biggest: %d \n", biggest);
```
|
Say I have:
```
char **search_terms = malloc(sizeof(char *) * number_search_terms);
for (i=0; i < number_search_terms; i++)
search_terms[i] = malloc(MAX_LINE_LEN);
```
When I free this memory, is it enough to do
```
free(search_terms)
```
or do I have to free each element in the buffer first, like this:
```
f... |
You have to free each buffer first, and then free the bigger buffer.freewill never traverse a tree to see if part of your data happens to be a pointer to othermalloced data.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ... |
You can usestrcmpto compare the text. Note that it returns a zero on a match:
```
if (strcmp(t, "int") == 0) {
printf("We have an integer\n");
}
```
|
I need to compare a basic file permission from a file with a file permission from input. The input should be saved inargv[1], and the permission information from file is stored in the classicalstruct stat stat_buf, specifically in thestat_buf.st_modefield.
An example of execution would be./program 775. Then the progr... |
the format ofst_modeis tricky because it has to be read as octal [...]
Not particularly. Just usestrtoul()with an appropriate base (8):
```
unsigned long mode = strtoul(argv[1], NULL, 8);
if (statbuf.st_mode == mode) {
// permissions match
}
```
|
I have just came across this code in c:
```
char buf[1024];
```
What does this mean? I was under the impressionchar *buf[1024]is the only way to make achara string.
|
The declaration
```
char *buf[1024];
```
makesbufan array of pointers tochar. In other words, it can be used as an array of 1024 strings.
The declaration
```
char buf[1024];
```
declares asinglearray of characters, that can contain up to 1024 characters (or a string with 1023 characters plus the terminator).
|
Suppose I have the following structure definition:-
```
struct structure
{
int a;
int array[];
}one;
```
How is the memory allocated for the above structure when the array size is unsepicified?
|
Assuming 32-bitintand 8-bitchar,sizeof oneis likely4. That is,arrayis an empty (zero-length) array. Normally you'd dynamically allocate a structure with a flexible array member:
```
struct structure *two = malloc(sizeof *two + 32 * sizeof(int));
```
Which makestwoa pointer to astruct structurewith 32 elements in i... |
Say I have:
```
char **search_terms = malloc(sizeof(char *) * number_search_terms);
for (i=0; i < number_search_terms; i++)
search_terms[i] = malloc(MAX_LINE_LEN);
```
When I free this memory, is it enough to do
```
free(search_terms)
```
or do I have to free each element in the buffer first, like this:
```
f... |
You have to free each buffer first, and then free the bigger buffer.freewill never traverse a tree to see if part of your data happens to be a pointer to othermalloced data.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ... |
You can usestrcmpto compare the text. Note that it returns a zero on a match:
```
if (strcmp(t, "int") == 0) {
printf("We have an integer\n");
}
```
|
I need to compare a basic file permission from a file with a file permission from input. The input should be saved inargv[1], and the permission information from file is stored in the classicalstruct stat stat_buf, specifically in thestat_buf.st_modefield.
An example of execution would be./program 775. Then the progr... |
the format ofst_modeis tricky because it has to be read as octal [...]
Not particularly. Just usestrtoul()with an appropriate base (8):
```
unsigned long mode = strtoul(argv[1], NULL, 8);
if (statbuf.st_mode == mode) {
// permissions match
}
```
|
I have just came across this code in c:
```
char buf[1024];
```
What does this mean? I was under the impressionchar *buf[1024]is the only way to make achara string.
|
The declaration
```
char *buf[1024];
```
makesbufan array of pointers tochar. In other words, it can be used as an array of 1024 strings.
The declaration
```
char buf[1024];
```
declares asinglearray of characters, that can contain up to 1024 characters (or a string with 1023 characters plus the terminator).
|
Suppose I have the following structure definition:-
```
struct structure
{
int a;
int array[];
}one;
```
How is the memory allocated for the above structure when the array size is unsepicified?
|
Assuming 32-bitintand 8-bitchar,sizeof oneis likely4. That is,arrayis an empty (zero-length) array. Normally you'd dynamically allocate a structure with a flexible array member:
```
struct structure *two = malloc(sizeof *two + 32 * sizeof(int));
```
Which makestwoa pointer to astruct structurewith 32 elements in i... |
I need help in writing a function in C/C++ that receives two parameters:IP addressandsubnetmask.
The function needs to reutrn a list of all IP addresses that are in the associated network.
For example:
Given two parameters:IP address= 192.168.33.72 andmask= 255.255.255.192
the function will return a list that conta... |
1) first you can transform theipaddressand thesubnetmaskfrom string format to binary format withinet_pton().
2) make a check on thesubnetmaskmask it should be a valid subnet mask
3) get thesubnetmaskinverse value (~subnetmask)
4)
```
for (i=1; i<(~subnetmask); i++) {
ip = ipaddress & (subnetmask + i);
//... |
```
int main(void)
{
int n, div, a, b;
double phi;
printf("Enter n:\n");
if (scanf("%d", &n) < 1 || n <= 0)
{
printf("Wrong input.\n");
return 1;
}
a = n;
div = 2;
phi = n;
while (n != 1)
{
if (n % div != 0)
div++;
else
{
n = n / div;
if (b != div)
{
... |
First check fordiv=2.
After that you only need to check odd numbers, so you can usediv += 2. That should cut the time in half.
|
I'm trying to compilemupdfon Windows 7 using mingw gcc. It is taking exception with the following line incontext.h
```
#define fz_throw(CTX, ERRCODE, MSG, ...) fz_throw_imp(CTX, __FILE__, __LINE__, ERRCODE, MSG, __VA_ARGS__)
```
With the error:
```
\mupdf\include/mupdf/fitz/context.h:70:105: error: expected express... |
This might help:
How to make a variadic macro (variable number of arguments)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.