question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I don't fully understand this, could someone help me evaluate the expression below? If message has**and length only has*, by using*()are we dereferencing to*messageandlength? Any help would be much appreciated.
```
bool func(char** message, size_t* length)
{
*(*message + *length) = '\0';
}
```
|
*(a + b)is another way of writinga[b]. The statement above is equivalent to
```
(*message)[*length] = '\0';
```
*messageis achar*string, and*lengthis a size. It sets the character at index*lengthto NUL.
There is no particular reason for the extra layer of pointers. It would be more normal to remove one*from each parameter and have the function be:
```
bool func(char* message, size_t length)
{
*(message + length) = '\0';
}
```
Or, in other words,
```
bool func(char* message, size_t length)
{
message[length] = '\0';
}
```
|
My code creates an array of 3 strings and attemps to populate each string using getline(). It also prints every string it gets:
```
int i;
size_t n = 100;
char (*words[3])[100];
for ( i = 0; i < 3; i++)
{
getline(&words[i], &n, stdin);
printf("%s\n",words[i] );
}
```
When I enter the third string in the command line I get a segmentation error.What's more, if I replace 3 with 5, I get the segmentation fault when I enter the first string.
So 1) How can I get the program to store all 3 or 5 or whatever strings I give it?, and2) Why if I replace 3 with 5 I get the error on the first string?
|
You have to declarewordsas an array of pointer and initialize it toNULLaccording to theman page:
```
char *words[3] = {NULL};
```
http://ideone.com/GxV9qy
|
Could anyone point out what is wrong with this piece of code? I'm trying to write a simple(without using arrays and stuff like that) program that would convert the base 10 numbers to any other base. I'm a beginner, I've just started coding in C.
PS: As you can see I haven't written anything that would inverse the results, and I didn't receive any outputs from the compiler. It stopped working.
```
main()
{
int a,b,c;
printf("Please enter a number in base 10: ");
scanf("%d",&a);
printf("\nPlease enter the base that you want the number to be converted to: ");
scanf("%d",&b);
do
{
c=a%b;
printf("%d",c);
a/=b;
}while(c!=0);
}
```
|
Change your while loop to a != 0. You want to loop until you have reduced the input number to zero. Your code is terminating when the first digit is 0.
|
Will the compiler make structure definition available in object file? Assume that I don't turn on flags like-g.
|
In general, no. C has no use for a structure definition once the code is compiled. The compiler will convert all the member references like this...
```
foo.x = 1;
```
...to assembly language that only knows thatxis a data item of a certain type at a certain offset from the beginning offoo. (Some hardware architectures may use a different addressing mechanism, but it will be conceptually the same.)
It's possible there's a compiler out there that embeds debug symbols in the object file rather than a separate debug file. I'm unaware of any such compilers, but one could exist. However, that's not really the same thing at all. Those symbols would probably only be loaded by a debugger and wouldn't be available to the program itself.
|
I'm working with linked lists. I'm having trouble accessing the data contained in a struct through a pointer. Here is my code:
```
void insertNode(Node **head, int num) {
Node *newNode = malloc(sizeof(Node));
newNode -> num = num;
while (head->next) { <-----problematic code
}
```
}
I've passed the address of the head pointer of the list into the function.
```
Node *list = malloc(arraySize * sizeof(Node));
Node *head = list;
insertNode(&head, randNum);
```
I keep getting an error that says "request for member "next" in something not a structure or union.
|
Node **headis a pointer to a pointer to aNode. Sohead->is dereferencing a pointer to a pointer and therefore gives you a pointer. A pointer is not a struct or union, hence the error. You can use:
```
(*head)->
```
to dereference the underlying node.
|
thank you in advance for any help you may provide. I'm trying to print a board of the "+" symbols based on values given for M and N (so if it was M:3 and N:1 it would come out as +++) but I am drawing an absolute blank on how you do that. The code is in C.
Edit: To clarify. I don't remember what I need to do to print the board based on the given values. I'm well aware that if I ran this code now it would come out blank.
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
int N, M;
printf("N: ");
scanf("%d",&N);
printf("M: ");
scanf("%d",&M);
printf("\n");
/* Show a board with N lines and M columns */
return 0;
}
```
|
to get you started
```
for(int i = 0; i < N; i++)
{
printf("X");
}
```
|
```
#include<stdio.h>
int main()
{
int a[2]={10,4};
int *k;
int *j;
j=a;
k=j;
printf("j=%d,k=%d\n\n",*j,*k);
*j++;
++*k;
printf("j=%d,k=%d",*j,*k);
return 0;
}
```
The output is:
j=10 k=10
j=4 k=11
I thought that it should have same result but this is not the case.
I wished to ask what is causing this difference. I didn't got the reason behind it.
|
You need to dig out your operator precedence table.
*p++is evaluated as*(p++)
++*pis evaluated as++(*p)
The second one is due to the prefix++having the same precedence as pointer dereference*soassociativity(which is from right to left for those operators) comes into play.
For completeness' sake,*(p++)dereferences the current value ofp, andpis increased by one once the statement completes.++(*p)adds 1 to the data pointed to byp.
|
I started studying C a week ago and decided to write my owntic-tac-toegame for practise.
I have a game loop inmain:
```
for(int i = 1; player1.isWinner!=1 || player2.isWinner!=1 || noWinner!=1; i++){...}
```
Wherei- counts turns and condition of end of the game is one of players has won, or no one has won (draw).
For now, it quits executing only ifallconditions are 1.
How can I make it work right?
|
Is a value of 1 where someone won?
If so, then you would need check any of those conditions is true and loop if they are not:
```
!(player1.isWinner==1 || player2.isWinner==1 || noWinner==1)
```
Or using AND, check and loop when none are set:
```
(player1.isWinner!=1 && player2.isWinner!=1 && noWinner!=1)
```
|
I know that I can open multiple connections to an In-Memory sqlite database usingfile:DB_NAME?mode=memory&cache=sharedinsqlite3_open_v2().
I open 2 connections to an In-Memory database. One with the flagsSQLITE_OPEN_URI | SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITEand another withSQLITE_OPEN_READONLY | SQLITE_OPEN_URI.
The problem is that sqlite lets me modify the database even when the connection is Read-Only.
Is there any way to make the connection Read-Only? Should I write my own VFS to accomplish it?
|
TheSQLITE_OPEN_READONLYflag affects how the database accesses any files and handles transactions.
Inshared-cache mode, multiple connections appear as a single connection in the interface to the file system. Therefore, they share the file access/transaction settings.
To prevent a connection from starting any write transactions, usePRAGMA query_only.
|
This question already has answers here:Is it good practice to free a NULL pointer in C? [duplicate](4 answers)Closed6 years ago.
Ì used to make sure a pointer was not null before freeing it, so I would normally destroy dynamically created structs like this:
```
Node *destroy_node(Node *node) {
if (node) {
free(node);
}
return NULL;
}
```
ButCERT MEM34suggests that since free() accepts null pointers, I could as well write
```
Node *destroy_node(Node *node) {
free(node);
return NULL;
}
```
Is that correct?
|
Yes, passingNULL(a null-pointer constant) tofree()is perfectly valid.
QuotingC11, chapter §7.22.3.3, (emphasis mine)
Thefreefunction causes the space pointed to byptrto be deallocated, that is, made
available for further allocation.Ifptris a null pointer, no action occurs.[...]
|
In javascript we can do the following:
```
var obj = {alpha: [1, 2, 3], omega:[1, 2, 3]};
function test(field) {
return obj[field];
}
test("alpha");
```
Now im trying to achieve the same in c using a typedef struct in c:
```
typedef struct FooBar{
char alpha[50];
char beta[50];
} FooBar;
FooBar fooBar;
int getTest(type field) {
return sizeof(fooBar.field);
}
getTest(alpha);
```
Is it possible to somehow just pass in a field name like shown above?
|
You could do it with a macro:
```
#define getTest(t) sizeof(fooBar.t)
typedef struct FooBar {
char alpha[50];
char beta[50];
} FooBar;
FooBar fooBar;
int main()
{
int alphasize = getTest(alpha);
}
```
But I'm not sure if this fulfills your requirement.
|
I got a task to modify the content of a 2-dimensional arrayint[5][5], I was given the definitionint *a[5][5]and ordered to use aint**(the pointer of a pointer) to handle this task.
I'm now wondering the meaning of thisint *a[5][5], how can I understand the meaning of this and similar definitions?
|
int *a[5][5]is a 2D array ofpointers. A pointer-to-pointer can be used to point at any pointer item in this array.
A for how to understand the declaration, everything left of the variable name is the type of each item in the array, in this caseint*.
You could also usethis site. It works for many C declarations, but not all.
|
Could anyone point out what is wrong with this piece of code? I'm trying to write a simple(without using arrays and stuff like that) program that would convert the base 10 numbers to any other base. I'm a beginner, I've just started coding in C.
PS: As you can see I haven't written anything that would inverse the results, and I didn't receive any outputs from the compiler. It stopped working.
```
main()
{
int a,b,c;
printf("Please enter a number in base 10: ");
scanf("%d",&a);
printf("\nPlease enter the base that you want the number to be converted to: ");
scanf("%d",&b);
do
{
c=a%b;
printf("%d",c);
a/=b;
}while(c!=0);
}
```
|
Change your while loop to a != 0. You want to loop until you have reduced the input number to zero. Your code is terminating when the first digit is 0.
|
Will the compiler make structure definition available in object file? Assume that I don't turn on flags like-g.
|
In general, no. C has no use for a structure definition once the code is compiled. The compiler will convert all the member references like this...
```
foo.x = 1;
```
...to assembly language that only knows thatxis a data item of a certain type at a certain offset from the beginning offoo. (Some hardware architectures may use a different addressing mechanism, but it will be conceptually the same.)
It's possible there's a compiler out there that embeds debug symbols in the object file rather than a separate debug file. I'm unaware of any such compilers, but one could exist. However, that's not really the same thing at all. Those symbols would probably only be loaded by a debugger and wouldn't be available to the program itself.
|
I'm working with linked lists. I'm having trouble accessing the data contained in a struct through a pointer. Here is my code:
```
void insertNode(Node **head, int num) {
Node *newNode = malloc(sizeof(Node));
newNode -> num = num;
while (head->next) { <-----problematic code
}
```
}
I've passed the address of the head pointer of the list into the function.
```
Node *list = malloc(arraySize * sizeof(Node));
Node *head = list;
insertNode(&head, randNum);
```
I keep getting an error that says "request for member "next" in something not a structure or union.
|
Node **headis a pointer to a pointer to aNode. Sohead->is dereferencing a pointer to a pointer and therefore gives you a pointer. A pointer is not a struct or union, hence the error. You can use:
```
(*head)->
```
to dereference the underlying node.
|
thank you in advance for any help you may provide. I'm trying to print a board of the "+" symbols based on values given for M and N (so if it was M:3 and N:1 it would come out as +++) but I am drawing an absolute blank on how you do that. The code is in C.
Edit: To clarify. I don't remember what I need to do to print the board based on the given values. I'm well aware that if I ran this code now it would come out blank.
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
int N, M;
printf("N: ");
scanf("%d",&N);
printf("M: ");
scanf("%d",&M);
printf("\n");
/* Show a board with N lines and M columns */
return 0;
}
```
|
to get you started
```
for(int i = 0; i < N; i++)
{
printf("X");
}
```
|
```
#include<stdio.h>
int main()
{
int a[2]={10,4};
int *k;
int *j;
j=a;
k=j;
printf("j=%d,k=%d\n\n",*j,*k);
*j++;
++*k;
printf("j=%d,k=%d",*j,*k);
return 0;
}
```
The output is:
j=10 k=10
j=4 k=11
I thought that it should have same result but this is not the case.
I wished to ask what is causing this difference. I didn't got the reason behind it.
|
You need to dig out your operator precedence table.
*p++is evaluated as*(p++)
++*pis evaluated as++(*p)
The second one is due to the prefix++having the same precedence as pointer dereference*soassociativity(which is from right to left for those operators) comes into play.
For completeness' sake,*(p++)dereferences the current value ofp, andpis increased by one once the statement completes.++(*p)adds 1 to the data pointed to byp.
|
I have iput two double variable in c and I need if one of the input is string terminate with print message i try something like this
```
double a, b;
printf("Input two variables:\n");
scanf("%lf %lf", &a, &b);
printf("%lf\n", a);
printf("%lf\n", b);
if(( a <= 0.0 ) || (b <= 0.0))
{
printf("Bad input\n");
return 2;
}
```
if I try input 4 fff (or fff 5) the program not print Bad input message.
Why this program not print Bad input message if set a=444 b=fff or a=ddd b=78?
|
You try and useabefore validating whether the input is valid. This could lead to unexpected behavior. You need to validate your input, something like:
```
if (scanf("%lf %lf", &a, &b) != 2) {
// handle bad input
}
```
|
```
#include <stdio.h>
int multiple(int, int);
int main()
{
int i;
int x;
int y;
scanf("%d %d", &x, &y);
printf("%d", multiple(x,y));
}
int multiple(int N,int M)
{
int i;
int result;
for (i=0;i*M<N;i++)
{
result=i*M;
printf("%d", result);
}
}
```
When I put input (for example x=100 and y=7) the output displays all the multiple until 105 and not until 98 as it should be.
|
The loop does print up to 98. However,multipleis declared to return anintbut doesn't actually have areturnstatement, so the return value is unspecified (and in practice you'll get some arbitrary value from a previous calculation). Then you print this "garbage" return value and in your case it happens to be 105.
If you don't wantmultipleto return a value then don't declare it to return a value, and don't print the value it returns.
|
I need to remove the first 3 characters from anarraywithout any libraries. How would I go about doing this? I know that I can usememmovebut I'm working on a system without the standard library, alsomemmoveis for pointers. WithmemmoveI can dothis:
```
void chopN(char *str, size_t n)
{
assert(n != 0 && str != 0);
size_t len = strlen(str);
if (n > len)
return; // Or: n = len;
memmove(str, str+n, len - n + 1);
}
```
But could I remove characters from an array withoutmemmoveor any other standard library functions?
|
As long as you know the string is at least 3 characters long, you can simply usestr + 3.
|
please can you help me with my easy program? I am begginer and my english is not good, it hard to understand. :/
PROGRAM:
```
void tisk_pole (P);
int main()
{
char P1[3][3]={{'1','2','3'},{'4','5','6'},{'7','8','9'}};
tisk_pole(P1);
return 0;
}
void tisk_pole (P){
int i, j;
for (i = 0; i < 3; i++){
for (j = 0; j < 3; j++)
printf("%c", P[i][j]); //HERE IS PROBLEM -> value is neither array nor pointer nor vector
putchar('\n');
}
}
```
PLEASE, can you help me solve this problem? Thank you very much.
|
You're missing the type declaration of the argumentP.
```
void tisk_pole(char P[3][3]) {
int i, j;
for (i = 0; i < 3; i++){
for (j = 0; j < 3; j++)
printf("%c", P[i][j]);
putchar('\n');
}
}
```
SeeC Function with parameter without type indicator still works?for how compilers treat a parameter with no type.
|
I want to print the values of phrs to terminal and check their data type. I thought I got the first part:
```
mexPrintf("Value: %d\n",prhs[0]);
```
But that's giving me junk. What am I missing? (Probably something obvious) Is there a way to check data types and print them out?
|
To check prhs date type, i think you can usemxGetClassName(prhs[0]). To print its value, you need to dereference it again, as I remember correctly. For example:
```
double* data = mxGetPr(prhs[0]);
mexPrintf("Value: %f\n",data[0]);
```
Note, mxGetPr, returns pointer to double, so left it in this example.
|
I have a .au audio file and am reading it in parts using fread. However when i write this to /dev/audio there is no sound being played. Do I need to do something or is the system supposed to play back as soon as I write to /dev/audio. I am not getting any errors.
```
player = open("/dev/audio", O_WRONLY, 0);
if (player < 0)
{
perror("Opening /dev/audio failed\n");
exit(1);
}
while(1)
{
//code to read from the file writes to buf 1000 bytes per read
//fread(buf,1000, 1, audioFile); //server side
write(player, buf, 1000);
}
```
|
The issue seems to be with Ubuntu. I tried the same on a Gentoo installation in my lab and the sound can be heard
|
I am writing a function in nasm that will be called from 32bit ansi C.
The function prototype in C looks like this:long double scalar(int n, long double *x)Where x is a pointer to an array oflong doubles.
The problem occurs when I try to load a singlelong doubleto the FPU:
```
mov ecx, [esp+8] ; n
mov eax, [esp+12] ; *x
fld [eax] ; ERROR: operation size not specified
```
How should I specify the size? My C compiler uses 12 bytes for a long double, how to fit it into the 80 bits?
|
To specify the size explicitely use the following form in NASM:
```
fld TWORD [eax] ; load 10 bytes from [eax]
```
As you pointed out, FPU stack registers are 80 bits wide. The C compiler chooses 12 bytes, because of the data alignment requirements of the stack frame.
|
Both Clang/LLVM and GCC show this warning. I am aware that headers must be included in order to use many functions, butstdio.his included at the top of the file. I've used other functions (e.g.,setbuf()) from the same header, and these work fine. Removing the header include causes errors and warnings to be thrown for these other functions, as expected.
I usedclang -MD -MFto show included header files and checked/usr/include/stdio.h, which contains a prototype forsetlinebuf(). I found one reference online tounix.h, but this doesn't appear to exist on my system.
I'm using Lubuntu 16.10 x86_64, Clang 3.8.1.
View source: Include on line 1, function use on line 32.
|
Include thisbeforeincludingstdio.h:
```
#define _BSD_SOURCE
```
setlinebuf()is not a standard C function and thus it may not be included by default instdio.h.
But note that_BSD_SOURCEhas been deprecated since glibc 2.20 and been superseded by_DEFAULT_SOURCE.
|
So, I have this program, where I store the line number in a variable, using
```
int x = __LINE__;
```
The value of x can keep changing.
Is it possible to jump from an arbitrary line to the one given by x, using goto or any other keyword in C?
I'm looking for something like
```
'keyword' x;
```
where the program shifts to a line defined by the variable x.
Is there a workaround if this is not possible?
|
The GCC compiler supports, as an extension,using labels as valuesso that you can work with them in a way that resembles what you're after.
It allows you to do:
```
void *ptr = &&label;
label:
```
and then
```
goto *ptr;
```
to jump tolabel.
This is typically useful inside the core of a virtual machine, and can of course lead to horrible spaghetti. Also, again, it's a GCC extension (also supported by Clang, I think).
|
I want to print the values of phrs to terminal and check their data type. I thought I got the first part:
```
mexPrintf("Value: %d\n",prhs[0]);
```
But that's giving me junk. What am I missing? (Probably something obvious) Is there a way to check data types and print them out?
|
To check prhs date type, i think you can usemxGetClassName(prhs[0]). To print its value, you need to dereference it again, as I remember correctly. For example:
```
double* data = mxGetPr(prhs[0]);
mexPrintf("Value: %f\n",data[0]);
```
Note, mxGetPr, returns pointer to double, so left it in this example.
|
First semester of CS.
When I change "%d" to "%f" the output is 10 times worse, not even showing the KPH row. Really not sure what I am doing wrong other than that.
This is a screenie of what happens as it is now.
Thanks for halpz I am n00b
```
#include<stdio.h>
float convertToMPH(float KPH);
float convertToKPH(float MPH);
int main(void){
int i;
puts("Kilometers per hour converted to miles per hour:");
puts("Kph\tMph");
for(i=185; i>=0; i-=5){
printf("%d\t%d\n", i, convertToMPH(i));
}
}
float convertToMPH(float KPH){
return (float) (KPH / 1.609344);
}
```
|
Change
```
printf("%d\t%d\n", i, convertToMPH(i));
```
to
```
printf("%d\t%f\n", i, convertToMPH(i));
```
|
I am reading the source code ofopen-iscsi. In this source files I see few functions start with prefix "__". Whats the reason behind naming a function with double underscore as prefix in general in C language?
Example: In the file usr/iscsi_sysfs.c, the function namestatic int __get_host_no_from_hwaddress(void *data, struct host_info *info)
Thanks for reading the post
|
These are reserved identifiers. Using them guarentees no naming collisions with user's code (assuming the users follow the convention).
7.1.3 Reserved identifiers....All identifiers that begin with an underscore and either an uppercase letter or another
underscore are always reserved for any use.
Such names shouldnotappear in third-party libraries, [email protected].'s comment.
|
I'm trying to make a tic tac toe program, but I have run into a warning. I know that the code still compiles, but I want to know why I have this warning and what I can do to fix it.
I get the warning when p = a;
```
void clean(){
char a[N][N], *p;
p = a;
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
*p++ = '_';
}
}
display(a);
}
void display(char a[N][N]){
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
printf("%c ", a[i][j]);
}
printf("\n");
}
}
```
|
Yourcleanfunction should be this:
```
void clean(void){
char a[N][N];
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
a[i][j] = '_';
}
}
display(a);
}
```
There is absolutely no advantage of having theppointer, except that your code is less readable.
|
I am not sure how to phrase this. But I have a C Program that will call another C Program in unix. After the call, the program(foo-exe) will prompt for an input "Y/N". I would like to suppress(hide) this prompting message and enter 'Y' thereafter as input. How do I go about doing that?
```
#include <stdio.h>
int main(int argc, char* argv[])
{
system("/home/xyz/foo-exe bar");
}
```
foo-exe
```
// do some other stuff
char ans = 'n';
printf("prompt message. Yes or no? (Y/N) ");
ans=getchar();
if(ans == 'Y') system("foo");
```
|
If that's all (Y or N) thefoo-exeexpects then you could redirect its stdin to read from a pipe.
```
system("echo Y | /home/xyz/foo-exe bar");
```
But be aware of thepitfallsofsystem()and its use is generally discouraged.
|
I thought using RegSaveKeyEx would help me to save a registry subkey as a .REG file, but it is not working. I have this code:
```
// Saving key
LONG saveKey = RegSaveKeyExW(keyResult, L"C:\\Demo1.reg", securityAttributes, Flags);
```
securityAttributesis set asNULL, andFlags, asREG_LATEST_FORMAT.
I don't have any problem by saving it as a .DAT file, but want a .REG one, like exporting the subkey from the Registry window itself.
This is how the .REG file looks like:
Not that I amnot talking about enabling or disabling privilegesin the access token, but using the function itself.
|
There is no Registry API function that will output a key in.regformat. You will have to enumerate the key's content yourself and write out your own.regfile manually.
|
I am learning unit testing using Ceedling, with CMock for mocks, on an existing, embedded C code-base (which I can adjust to suit).
I have come across the situation where one function in a unit calls a second function within the same unit.
```
int foo_a(int r)
{
/* foo_a work */
/* do not wish to test this function just to test foo_b. */
}
int foo_b(int i) /* function to test */
{
/* foo_b work */
if (some_condition)
foo_a(k); /* need to test if foo_a() is called or not. */
}
```
I don't want to test thefoo_a()as part of thefoo_b()tests. How do I mockfoo_a()so that I can still test if it is called or not but without testing thefoo_a()function itself?
|
You can't do this without modifying your source code.
Consider breaking the functions out into two separate compilation units.
Or, add an#ifndef TESTaround the function you want to replace.
|
I am not sure how to phrase this. But I have a C Program that will call another C Program in unix. After the call, the program(foo-exe) will prompt for an input "Y/N". I would like to suppress(hide) this prompting message and enter 'Y' thereafter as input. How do I go about doing that?
```
#include <stdio.h>
int main(int argc, char* argv[])
{
system("/home/xyz/foo-exe bar");
}
```
foo-exe
```
// do some other stuff
char ans = 'n';
printf("prompt message. Yes or no? (Y/N) ");
ans=getchar();
if(ans == 'Y') system("foo");
```
|
If that's all (Y or N) thefoo-exeexpects then you could redirect its stdin to read from a pipe.
```
system("echo Y | /home/xyz/foo-exe bar");
```
But be aware of thepitfallsofsystem()and its use is generally discouraged.
|
I thought using RegSaveKeyEx would help me to save a registry subkey as a .REG file, but it is not working. I have this code:
```
// Saving key
LONG saveKey = RegSaveKeyExW(keyResult, L"C:\\Demo1.reg", securityAttributes, Flags);
```
securityAttributesis set asNULL, andFlags, asREG_LATEST_FORMAT.
I don't have any problem by saving it as a .DAT file, but want a .REG one, like exporting the subkey from the Registry window itself.
This is how the .REG file looks like:
Not that I amnot talking about enabling or disabling privilegesin the access token, but using the function itself.
|
There is no Registry API function that will output a key in.regformat. You will have to enumerate the key's content yourself and write out your own.regfile manually.
|
I am learning unit testing using Ceedling, with CMock for mocks, on an existing, embedded C code-base (which I can adjust to suit).
I have come across the situation where one function in a unit calls a second function within the same unit.
```
int foo_a(int r)
{
/* foo_a work */
/* do not wish to test this function just to test foo_b. */
}
int foo_b(int i) /* function to test */
{
/* foo_b work */
if (some_condition)
foo_a(k); /* need to test if foo_a() is called or not. */
}
```
I don't want to test thefoo_a()as part of thefoo_b()tests. How do I mockfoo_a()so that I can still test if it is called or not but without testing thefoo_a()function itself?
|
You can't do this without modifying your source code.
Consider breaking the functions out into two separate compilation units.
Or, add an#ifndef TESTaround the function you want to replace.
|
I am working on compiler design for 8051. I want to declare a memory of say 30 locations, each location is of 8bits. How do I declare that in C?
|
to declare 30 x 8 bits memory:
```
char memory[30];
```
to declare n x n memory:
```
char memory[30][30];
```
it declares 30 x 30 x 8bits memory.
|
I have a basic question, which is bugging me a lot and I am unable to figure out why a programmer uses it.
```
if (0 == Indx)
{
//do something
}
```
What does the above code do and how is it different from the one below.
```
if (Indx == 0)
{
// do something
}
```
I am trying to understand some source code written for embedded systems.
|
Some programmers prefer to use this:
```
if (0 == Indx)
```
because this line
```
if (Indx == 0)
```
can "easily" be coded by mistake like an assignment statement (instead of comparison)
```
if (Indx = 0) //assignment, not comparison.
```
And it is completely valid in C.
Indx = 0is an expression returning 0 (which also assigns 0 to Indx).
Like mentioned in the comments of this answer, most modern compilers will show you warnings if you have an assignment like that inside an if.
You can read more about advantages vs disadvantageshere.
|
Here's the sample structure.
```
main.c
|
--------------
|
dir0-"sum.h","sum.c"
```
sumandsubare just two simple functions, located indir0. They're called inmain.c.
I'm trying to compile using gccgcc -Idir0 main.c sum.c -o main.
But it throws an error that it cannot findsum.c.
Besides, how to use-Iflag with two sub-directory.
|
The command should be:
```
gcc -Idir0 main.c dir0/sum.c -o main
```
Notice that sum.c is in a sub-directory and you have to tell the compiler that.
|
I have a basic question, which is bugging me a lot and I am unable to figure out why a programmer uses it.
```
if (0 == Indx)
{
//do something
}
```
What does the above code do and how is it different from the one below.
```
if (Indx == 0)
{
// do something
}
```
I am trying to understand some source code written for embedded systems.
|
Some programmers prefer to use this:
```
if (0 == Indx)
```
because this line
```
if (Indx == 0)
```
can "easily" be coded by mistake like an assignment statement (instead of comparison)
```
if (Indx = 0) //assignment, not comparison.
```
And it is completely valid in C.
Indx = 0is an expression returning 0 (which also assigns 0 to Indx).
Like mentioned in the comments of this answer, most modern compilers will show you warnings if you have an assignment like that inside an if.
You can read more about advantages vs disadvantageshere.
|
Here's the sample structure.
```
main.c
|
--------------
|
dir0-"sum.h","sum.c"
```
sumandsubare just two simple functions, located indir0. They're called inmain.c.
I'm trying to compile using gccgcc -Idir0 main.c sum.c -o main.
But it throws an error that it cannot findsum.c.
Besides, how to use-Iflag with two sub-directory.
|
The command should be:
```
gcc -Idir0 main.c dir0/sum.c -o main
```
Notice that sum.c is in a sub-directory and you have to tell the compiler that.
|
I am writing two c files that one is to write(by stdout) and another is read(by stdin).
But the read code is always hangs with read(), I have tried fread function but useless.
Can someone give advice?
Write example:
```
int main() {
char *a_string="Hello";
write(fileno(stdout), a_string, strlen(a_string)+1);
return 0;
}
```
Read example:
```
int main() {
char buffer[100];
read(fileno(stdin), buffer, 100-1);
printf("buffer=%s\n", buffer);
return 0;
}
```
|
The read code is always hangs with read(), I have tried fread function but useless.
This is becausereadandfread, unlikefgetsand similar functions, do not quit reading when the user inputs a newline (pressesEnter). It waits until EOF is read or until the specified bytes have been read.
To send EOF toreadyou must pressCtrl+D.
|
I was tracing a piece of code for a program works in embedded Linux and encountered this. I couldn't google out useful information to show me how it really works.
This piece of code is written like:
```
unsigned char foo(*someaddress){
unsigned long flags = 0; //why use a long?
flags = save_and_cli(); //what is this?
spin_lock_irqsave(&someaddress, flags);//ok, this is a spin lock
...do something...
restore_flags(flags); //release something?
spin_unlock_irqrestore(&someaddress, flags);//release lock
}
```
It seems this LONG flags' value is never changed and what is save_and_cli() function?
Thanks if you reading this.
|
IIRCsave_and_cliis an "ancient" version oflocal_irq_save
It saves the current state of local interrupt delivery and then disable it.
Functionlocal_irq_restoreis used to restore irq state saved bylocal_irq_save
Here for reference
|
How can I access piped parameter in c code?
test.c
```
int main( int argc, char *argv[] ) {
int i = 0;
for (i = 0; i < argc; i++) {
printf("argv[%d] = %s\n", i, argv[i]);
}
}
```
Bash:
```
cat file.txt | ./test
```
It prints just first argumentargv[0] = ./test. How can I access content of file.txt inside c code (as parameter)?
|
With the pipe, your program gets the content offile.txtin its stdin. So, read fromstdin. For example you can usefgets()to read line by line:
```
#include <stdio.h>
int main(int argc, char *argv[]) {
int i = 0;
char line[1024];
while(fgets(line, sizeof line, stdin)) {
printf("%s", line);
}
}
```
|
hi to all i have this problem i have a array of uint8_t
uint8_t command_Text[256]
i read some data from adc, i use snprintf for convert the data float in uint8_t
```
` float aux;
uint8_t value[4];
aux=(float)(HAL_ADC_GetValue(&hadc))
snprintf(value,4,"%.0f",aux); //convert the data float to uint8_t
strcat(command_Text, value); //append data `
```
i see this Warning argument of type "uint8_t *" is incompatible with parameter of type "char const *
i don't know manipolate the string in uint_8 data, i want read data e to append it in to array, can you help me?
|
Suggest something like:
```
uint8_t command_Text[256] = {'\0'};
....
uint8_t value[4] = {'\0'};
snprintf(value,3,"%3.3u", atoi( HAL_ADC_GetValue( &hadc ) ) );
strcat(command_Text, value); //append data
```
|
```
int sarl_n(int x, char n){
x <<= 2;
x >>= n;
return x;
```
}
When I assemble with "gcc -m32 -S sarl_n.c", it emits this code:
```
.cfi_startproc
movl 4(%esp), %eax
movsbl 8(%esp), %ecx
sall $2, %eax
sarl %cl, %eax #This is the part which I don't understand
ret
.cfi_endproc
```
Why is gcc using the "mini register"%clinstead of the big one%ecx?
EDIT: I used the O2 option to get shorter assembly code
|
The reason why the following line(previous version) in question
```
sarl %cl, 8(%ebp) #This is the part which I don't understand
```
or (current version)
```
sarl %cl, %eax #This is the part which I don't understand
```
is using the%cland not%ecxis, that theSARopcode only supports the%clregister as an input for a variable arithmetic shift(by%cltimes).
Seehere, and I quote:
```
SAR r/m32, CL MC Valid Valid Signed divide* r/m32 by 2, CL times.
```
|
What is the exact equivalent of the following function for Ubuntu?
http://www.qnx.com/developers/docs/6.4.1/neutrino/lib_ref/e/endian_be16.html
|
What you need is:
```
#include <endian.h>
result_in_host_endianness = be16toh(my_big_endian_number)
```
Seehttp://man7.org/linux/man-pages/man3/endian.3.html
|
Got confused with the following peice of code.
```
#include <stdio.h>
void main()
{
int a=0100;
printf("%x",a);
}
```
The value I am getting is 40.
Can someone explain me whats going on here?
Note : When I removed the digit 0 before digit 1 then its coming 64 which is correct, when 100 is converted into hex.
Codepad link to above code
|
In C, a constant prefixed with a0is anoctalconstant. 0100 in base 8 is
1000000 in base 2, which is 40 in hexadecimal, which is 64 in base 10. So your program is printing exactly what it should.
|
What is the exact equivalent of the following function for Ubuntu?
http://www.qnx.com/developers/docs/6.4.1/neutrino/lib_ref/e/endian_be16.html
|
What you need is:
```
#include <endian.h>
result_in_host_endianness = be16toh(my_big_endian_number)
```
Seehttp://man7.org/linux/man-pages/man3/endian.3.html
|
Got confused with the following peice of code.
```
#include <stdio.h>
void main()
{
int a=0100;
printf("%x",a);
}
```
The value I am getting is 40.
Can someone explain me whats going on here?
Note : When I removed the digit 0 before digit 1 then its coming 64 which is correct, when 100 is converted into hex.
Codepad link to above code
|
In C, a constant prefixed with a0is anoctalconstant. 0100 in base 8 is
1000000 in base 2, which is 40 in hexadecimal, which is 64 in base 10. So your program is printing exactly what it should.
|
Learning C and need to populate array of five struct elements but I can't seem to figure out how to pass the struct array to a function and I keep getting error:
```
error: conflicting types for 'dealFiveHand'
```
Here is the code:
```
#define HAND_SIZE 5
void dealFiveHand(struct Card *wHand[]);
struct Card {
char suit;
char face;
};
int main(void)
{
struct Card *hand[HAND_SIZE];
dealFiveHand(hand);
}
void dealFiveHand(struct Card *wHand[])
{
...
}
```
Do I need to define and initialize a pointer and then pass that pointer to the function?
|
At least you need to move the definition ofstruct CardBEFORE functiondealFiveHandprototype - that way the function knows about the type of its parameter.
```
struct Card {
char suit;
char face;
};
void dealFiveHand(struct Card *wHand[]);
```
|
I am writing some where I need to divide 29 by 10. But when I do so and store it in a double, it outputs 2.0000 instead of 2.9. Can someone explain why this is happening and how to fix it?
```
double a = 29/10;
output: 2.0000
```
|
Thedoubleworks as expected, it's just that you are not assigning it an expression of typedouble.
What you assign it is anint, a result of dividing29, anint, by10, anint. This is2, because the remainder is discarded when you divide integers.
Changing29to29.0or10to10.0will fix this problem.
|
```
schedule_accept(int fd,
int (*handler)(int, FdEventHandlerPtr, AcceptRequestPtr),
void *data)
```
Apologies for seeming to avoid searching for an answer here but I don't know what the constructs are in order to search intelligently for them. Specifically I'm interested in what the second parameter means?
My best guess is it's an int (that refers to a memory location) that is composed(?) of a tuple of the three referred to types. Is this correct? If I was only interested in one of these (and I'm right in my description in the first place) how would I refer to it?
|
```
int (*handler)(int, FdEventHandlerPtr, AcceptRequestPtr)
```
Defines a parameter namedhandlerwhich is a pointer (hence the*) to a function, which returns anint(hence the "outer"int) and takes three arguments, namely oneint, oneFdEventHandlerPtrand oneAcceptRequestPtr.
|
I want to know exactly, what is a null statement in C programming language? And explain a typical use of it.
I found the following segment of code.
```
for (j=6; j>0; j++)
;
```
And
```
for (j=6; j>0; j++)
```
|
From themsdnpage:
The "null statement" is an expression statement with the expression missing. It is useful when the syntax of the language calls for a statement but no expression evaluation. It consists of a semicolon.Null statements are commonly used as placeholders in iteration statements or as statements on which to place labels at the end of compound statements or functions.
know more:https://msdn.microsoft.com/en-us/library/1zea45ac.aspx
And explain a typical use of it.
When you want to find the index of first occurrence of a certain character in a string
```
int a[50] = "lord of the rings";
int i;
for(i = 0; a[i] != 't'; i++)
;//null statement
//as no operation is required
```
|
I sawthisquestion but none of the answers were quite what I was looking for. I've triedstrstrbut it returns a pointer instead of an integer index.
I need to find if stringacontains stringband if so, where it's located, kind of like the index returned bystrcmp. Is there a function or easy way to do this in C?
For example, ifais "foobar" andbis "bar", then this function/method would return 3 because "bar" is at index 3 of "foobar".
Any help is appreciated!
|
You can usestrstrfor this, along with some pointer arithmetic.
```
char *result = strstr(a, b);
if (result != NULL) {
printf("index = %tu\n", result - a);
}
```
Here,resultpoints a particular number of bytes ahead ofa. So if you subtract the two, that's your index.
|
I'm making a project where I need to mirror an image vertically. The image is read by a function and then set into an array pixel by pixel, to move through this array I am usingarray[idy*w + idx](w being the width of the matrix or image in my case) now, since this will run concurrently I only need to find the opposite pixel so that I can assign it.
I mean something like this:
```
array[idy*w + idx] = array[opposite pixel];
array[opposite pixel] = array[idy*w + idx];
```
The problem is I can't find the proper way to do it.
Any answer would be highly appreciated.
I have tried doing the following but it doesn't workarray[idy*w + (w - (idx + 1))]
|
This is what worked for me in the end:
```
outputImage[idy*w + idx] = inputImage[idy*w + (w - idx - 1)];
```
|
Although otherwise working with pointers, all Xlib functions I've seen so far pass their Window struct by value, not by reference. E.g.:
https://tronche.com/gui/x/xlib/ICC/client-to-window-manager/XGetClassHint.html
https://tronche.com/gui/x/xlib/window/XDestroyWindow.html
Is there any particular rationale for that? In particular, in the case of XGetClassHint, the first and third parameters are passed by reference but the second isn't.
|
It looks likeWindowin those examples isn't a struct; it's just an unsigned long. That is, given:
```
#include <X11/X.h>
Window w;
```
If I pass that throughgcc -EI see:
```
$ gcc -E wintest.c | grep Window
typedef XID Window;
Window w;
```
AndXIDis:
```
$ gcc -E wintest.c | grep XID
typedef unsigned long XID;
```
|
I am trying to compile kernel for Cyanogenmod 13. I am getting error
```
ERROR: modpost: Found 2 section mismatch(es).
To see full details build your kernel with:
'make CONFIG_DEBUG_SECTION_MISMATCH=y'
To build the kernel despite the mismatches, build with:
'make CONFIG_NO_ERROR_ON_MISMATCH=y'
(NOTE: This is not recommended)
```
I read ithere. That i need to compile my kernel using 4.7.
How can i choose the version of toolchain during cyanogenmod build ??
|
I believe you need to setup gcc version 4.7 and use CC variable to set it as a compiler. E.g.make target CC=/bin/gcc4.7
More informationhereandhere.
|
I have a c file I've compiled with a executable called "run"
And want to run it with a argv[1] of testfile.txt that is in the uploads directory.
This here seems to work, but I don't understand why.
```
exec(__DIR__ . '/run uploads/testfile.txt',$output);
```
C programs are run as such:
```
./run uploads/testfile.txt
```
Adding a dot to the beginning of the exec() command makes it not work, but I'm running an executable, not a file (not a file run), why does the first example work but the other doesn't?
This doesn't work but it should?
```
exec(__DIR__ . './run uploads/testfile.txt',$output);
```
Where./runis the c executable, andargv[1]is in the uploads directory which istestfile.txt
|
Suppose__DIR__=='/foo/bar'.
Then,__DIR__ . './run'would evaluate to/foo/bar./runwhich does not exist.
|
I was studying ANSI C programming language and it says in introduction:
"Local variables are typically "automatic," or created anew with each invocation."
I'm guessing allocating and deallocating variables work with stack frame logic of Java. So are global variables automatic too? They would get in and out of stack frame much less than local variables since they are in the scope of the whole .c file.
|
No, these concepts don't play each other. The term global variable is an informal notion, that refers to variables with external linkage. By definition, the automatic variables have no linkage, hence it does not make sense to have variable, that is both automatic and global.
|
I sawthisquestion but none of the answers were quite what I was looking for. I've triedstrstrbut it returns a pointer instead of an integer index.
I need to find if stringacontains stringband if so, where it's located, kind of like the index returned bystrcmp. Is there a function or easy way to do this in C?
For example, ifais "foobar" andbis "bar", then this function/method would return 3 because "bar" is at index 3 of "foobar".
Any help is appreciated!
|
You can usestrstrfor this, along with some pointer arithmetic.
```
char *result = strstr(a, b);
if (result != NULL) {
printf("index = %tu\n", result - a);
}
```
Here,resultpoints a particular number of bytes ahead ofa. So if you subtract the two, that's your index.
|
I'm making a project where I need to mirror an image vertically. The image is read by a function and then set into an array pixel by pixel, to move through this array I am usingarray[idy*w + idx](w being the width of the matrix or image in my case) now, since this will run concurrently I only need to find the opposite pixel so that I can assign it.
I mean something like this:
```
array[idy*w + idx] = array[opposite pixel];
array[opposite pixel] = array[idy*w + idx];
```
The problem is I can't find the proper way to do it.
Any answer would be highly appreciated.
I have tried doing the following but it doesn't workarray[idy*w + (w - (idx + 1))]
|
This is what worked for me in the end:
```
outputImage[idy*w + idx] = inputImage[idy*w + (w - idx - 1)];
```
|
When softwares such as ecryptfs use AES, it asks for a user password (such as "password123").
The AES algorithm by itself does not call for a user password. So where does the "password123" get thrown into the math?
I'm working to make a C function that encrypts some data using a password. I know the typical way of doing it with OpenSSL and an aes key, but I don't know how to get a user password integrated.
|
You need to use a key derivation function (KDF). Password-Based Key Derivation Function 2 (PBKDF2) is the current most common approach.
OpenSSL probably exposes PBKDF2, it typically takes in a password and an iteration count (modern systems should use something like 100000 or higher... crank up the number until it takes about 0.3 seconds), and an output length. It may also take a hash function, something in the SHA-2 family (SHA256, SHA384, SHA512) would be a good modern choice.
|
Can anyone please explain me why is this code printing 1 3 0 0 0 -1, and not 1 2 3 0 0 0? How does this call of define work?
```
#include<stdio.h>
#define SOMETHINGDEFINED(i) A[i%4]
int main(void) {
int i, A[6] = { 1 };
SOMETHINGDEFINED(1) = 2;
SOMETHINGDEFINED(5) = 3;
SOMETHINGDEFINED(4 + 2) = SOMETHINGDEFINED(1 + 3 + 1)--;
for (i = 0; i < 6; i++) {
printf("%d ", A[i]);
}
return 0;
}
```
|
#definedoes a textual replacement, so
```
SOMETHINGDEFINED(1 + 3 + 1)--
```
becomes
```
A[1 + 3 + 1%4]--
```
Now you can see that modulo is only applied to last operand, not to the whole expression. You have to define the macro as
```
#define SOMETHINGDEFINED(i) A[(i)%4]
```
to correctly apply it to the whole expression.
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed6 years ago.Improve this question
```
int main()
{
int i;
int v = 5;
for (i = 0; v; i++)
{
v &= (v - 1);
printf("%d\n", v);
}
return 0;
}
```
I know it will exit after two iterations, but why?
|
You need to look at the binary representation and remember that&is a bit-wise and-operator:
```
v = 5 = 101b
// First loop
v = 5 & (5-1) = 5 & 4 = 101b & 100b = 100b = 4
// Second loop
v = 4 & (4-1) = 4 & 3 = 100b & 011b = 000b = 0
// No more loops
```
|
● int vectorInsert(Vector * array, int index, Data value);
I am doing
If this can be corrected according to the given statement.
I am calling it using
```
Vector *vect = initVector();
Data data_array[20];
for(i = 0 ; i < 20 ; i++){
data_array[i].value = (rand() % 20) + 1;
vectorInsert(vect, i, data_array[i]);
}
```
|
There are a couple of errors in your code, but the most important one is in yourinitVectorfunction, you actually need to allocate memory for the vector.
You also need to do the following things:
ininitVectorreturnvinstead ofv->dataor&vinvectorInsertprintarray->data[index].valueinstead ofarray->data[index]invectorInsertreturn1on success, add error checking in your allocation and return0on memory error.
All of these except the original malloc were warnings returned by the compiler.
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed6 years ago.Improve this question
```
int main()
{
int i;
int v = 5;
for (i = 0; v; i++)
{
v &= (v - 1);
printf("%d\n", v);
}
return 0;
}
```
I know it will exit after two iterations, but why?
|
You need to look at the binary representation and remember that&is a bit-wise and-operator:
```
v = 5 = 101b
// First loop
v = 5 & (5-1) = 5 & 4 = 101b & 100b = 100b = 4
// Second loop
v = 4 & (4-1) = 4 & 3 = 100b & 011b = 000b = 0
// No more loops
```
|
● int vectorInsert(Vector * array, int index, Data value);
I am doing
If this can be corrected according to the given statement.
I am calling it using
```
Vector *vect = initVector();
Data data_array[20];
for(i = 0 ; i < 20 ; i++){
data_array[i].value = (rand() % 20) + 1;
vectorInsert(vect, i, data_array[i]);
}
```
|
There are a couple of errors in your code, but the most important one is in yourinitVectorfunction, you actually need to allocate memory for the vector.
You also need to do the following things:
ininitVectorreturnvinstead ofv->dataor&vinvectorInsertprintarray->data[index].valueinstead ofarray->data[index]invectorInsertreturn1on success, add error checking in your allocation and return0on memory error.
All of these except the original malloc were warnings returned by the compiler.
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed6 years ago.Improve this question
I have the following code:
```
if (a1 < a2)
a3=0;
else
a3=a1-a2;
if (b1 < b2)
b3=0;
else
b3=b1-b2;
if (c1 < c2)
c3=0;
else
c3=c1-c2;
```
The code is quite repetitive. Any suggestions on optimize code size? I do not want to use array.
|
You can use a macro like:
```
#define COM(x,y) ((x<y)?0:(x-y))
...
a3 = COM(a1,a2);
b3 = COM(b1,b2);
c3 = COM(c1,c2);
```
or use a function instead.
```
int func(int x, int y)
{
return (x<y)?0:(x-y);
}
a3 = func(a1,a2);
b3 = func(b1,b2);
c3 = func(c1,c2);
```
If you can use an array (for storing a, b, and c etc) for storing these values, then you can use a simple loop instead of repeating the macro/function call.
|
Is there a way to catch a signal just once withsigactionstructure and function? To be more specific, I would like to simply reset to default a specific signal (SIGINT). Is it possible to achieve this in a handler?
Edit
So, something like this would be correct:
void sig_int(int sig)
{
printf(" -> Ctrl-C\n");
struct sigaction act;
act.sa_handler = SIG_DFL;
if(sigaction(SIGINT, &act, NULL) < 0)
{
exit(-1);
}
}
int main()
{
struct sigaction act;
act.sa_handler = sig_int;
if(sigaction(SIGINT, &act, NULL) < 0)
{
exit(-1);
}
while(1)
{
sleep(1);
}
return 0;
}
|
The standard SA_RESETHAND flag, set in thesa_flagsmember ofstruct sigaction, does precisely this.
Set that flag when specifying your SIGINT handler, and the handler will be reset to SIG_DFL upon entry.
|
If I do this assignment
```
float x = 16.8;
unsigned int i = *(unsigned int*) &x;
```
What will be the value of the variablei? What it is the logic of this assignment?
|
With a code like this, you could have seen the answerin your precise case:
```
#include <stdio.h>
int main(void)
{
float x = 1;
unsigned int i = *(unsigned int*) &x;
printf("%d\n", i);
return 0;
}
```
This type of assignment is illegal, by casting a pointer to afloatinto a pointer to anunsigned int, then dereferencing it, you are against theStrict Aliasing Rule.
As it was said in the comments, there is no strict answer.
Even if with a roundedxlike :
```
float x = 16;
```
You will probably not have an expectedi = 16.
In most cases, your code will seem correct, you will not be warned or anything, and you code will run.So be careful!
|
Consider this snippet:
```
void init_seed(char *key)
{
char *seed = key;
size_t seed_len = strlen(seed);
// Make sure the seed is at least 12 bytes long
if (seed_len < 12) {
char new_seed[13];
for (int i = 0; i < 12; i++)
new_seed[i] = seed[i % seed_len];
new_seed[12] = '\0';
seed = new_seed;
}
/* Use the seed variable */
}
```
The reason I declared it this way is that I donotwant to usemalloc()in this function, because it will complicate the function quite a lot.
The function works as intended (gcc 4.8.4). However, does declaringnew_seedinside the if statement and then assigning it toseedcause undefined behavior?
|
Yes.
Oncenew_seedis out of scope, you no longer own any memory that was allocated for it.
So the behaviour on dereferencing the newly assigned value ofseedisundefined.
|
I am trying to add logging to the web proxy Polipo and as part of this need to log the url request in the following functionfollowing line:
```
httpClientRequest(HTTPRequestPtr request, AtomPtr url)
```
From compilation I see that AtomPtr is a struct of type_Atombut I cannot find where this is defined so that I can reference the text of the url in a log statement. What is the canonical method of looking up struct definitions in C code?
|
you can searchAtomPtrlikethisand see where AtomPtr is defined
```
typedef struct _Atom {
unsigned int refcount;
struct _Atom *next;
unsigned short length;
char string[1];
} AtomRec, *AtomPtr;
```
|
For a peripheral requirement in an embedded system, I have to declare a variable to read a register, but won't use the value later. Hence, I get compiler warning about my unused variable naturally.
How can I suppress the warning? I have 2 ways in mind:
using compiler directives, I hesitate because they are compiler-dependentadding a dummy read from variable, like:volatile int var;
var = peripheral_register;
var = var;
Do you have a better idea?
|
If all you need to do is read the register (to clear some status flag for example), then you do not need a receiving variable at all just:
```
(void)peripheral_register ;
```
is sufficient assuming the register is itself is declared volatile so that it must be read.
Otherwise you could make your dummyvarglobal with external linkage - that way the compiler cannot determine that it is not read elsewhere; but that's a far uglier solution.
|
Is there a way to catch a signal just once withsigactionstructure and function? To be more specific, I would like to simply reset to default a specific signal (SIGINT). Is it possible to achieve this in a handler?
Edit
So, something like this would be correct:
void sig_int(int sig)
{
printf(" -> Ctrl-C\n");
struct sigaction act;
act.sa_handler = SIG_DFL;
if(sigaction(SIGINT, &act, NULL) < 0)
{
exit(-1);
}
}
int main()
{
struct sigaction act;
act.sa_handler = sig_int;
if(sigaction(SIGINT, &act, NULL) < 0)
{
exit(-1);
}
while(1)
{
sleep(1);
}
return 0;
}
|
The standard SA_RESETHAND flag, set in thesa_flagsmember ofstruct sigaction, does precisely this.
Set that flag when specifying your SIGINT handler, and the handler will be reset to SIG_DFL upon entry.
|
If I do this assignment
```
float x = 16.8;
unsigned int i = *(unsigned int*) &x;
```
What will be the value of the variablei? What it is the logic of this assignment?
|
With a code like this, you could have seen the answerin your precise case:
```
#include <stdio.h>
int main(void)
{
float x = 1;
unsigned int i = *(unsigned int*) &x;
printf("%d\n", i);
return 0;
}
```
This type of assignment is illegal, by casting a pointer to afloatinto a pointer to anunsigned int, then dereferencing it, you are against theStrict Aliasing Rule.
As it was said in the comments, there is no strict answer.
Even if with a roundedxlike :
```
float x = 16;
```
You will probably not have an expectedi = 16.
In most cases, your code will seem correct, you will not be warned or anything, and you code will run.So be careful!
|
Take for instance the following example of calling a function, and assigning a value to one of its parameters at call time:
```
int MyFunction(int flag, float value);
MyFunction(myFlag=666, 3.14);
```
It's legal, though perhaps dangerous, to assign values to variables in a function call's parameter list.
How can I do something similar when a function's parameter may be a structure?
```
typedef struct
{
int i, j;
float k;
} my_struct;
int MyFunction(my_struct values);
myValues.i = 666;
myValues.k = 3.14;
MyFunction(myValues);
// how about this instead:
MyFunction({myValues.j=777}); // or something similar?
```
|
You can assign a compound literal to the variable:
```
MyFunction(myValues = (my_struct) {myValues.i, .j=777, myValues.k});
```
|
I'm trying to execute this code:
```
signal(SIGALRM,handler);
alarm(1);
while(1){}
```
Thehandlerfunction just prints "test".
alarm(1)will eventually be executed only one time in this case. I tried to put it in the loop and it seems that it doesn't get executed at all!
I am kinda new to signals. Can someone explains to me how this happens?
|
If you just putalarm(1)in the loop in your example, you'll callalarm(1)infinitely many times within a few microseconds of each invocation. And thenthishappens:
If an alarm has already been set with alarm() but has not been delivered, another call to alarm() will supersede the prior call.
I.e., the alarm gets cleared in each iteration of the loop. And since your loop runs forever, the alarm is never permanently set.
|
I tried doing awhileloop with multiple conditions, but I just can't figure out how to make it work. I've made a short example of what I kind of tried:
```
#include <stdio.h>
int main () {
int Num;
printf("Please enter an odd integer between 5-20: ");
scanf("%d", &Num);
while ((Num % 2 == 0) && (5 > Num) && (20 < Num)) {
printf("Not a valid input!");
printf("Please enter an odd integer between 5-20: ");
scanf("%d", &Num);
}
}
```
I believe I'm using the correct logical operator, right?
|
Nope, you're wrong. Think of the logic
```
(5>Num) && (20<Num)
```
Numcannot be<5and>20at the same time. You either
need the logical OR operatorChange the range to something like(Num > 5) && (Num < 20)or something
|
I need to make a Julia type corresponding to a C struct that has a fixed size array:
```
struct cstruct {
...
int arr[N] //N known at compile time
...
};
```
I have defined Julia types corresponding to other C structs with arrays like this:
```
type jstruct
...
arr::Ptr{Cint}
...
end
```
But as I understand it, this only works whenarris a pointer, not an array of a specific size. How can I ensure that the offsets of elements coming afterarrremain the same in both languages?
|
When you define a C struct with a fixed size array (or with the array hack), the data are stored directly inline within that struct. It's not a pointer to another region. The equivalent Julia structure is:
```
type JStruct{N}
arr::NTuple{N,Int}
end
```
That will store the integers directly inline within the struct.
|
I have to write program that displays the nth roots of unity when given a positive integer n. It's a programming project 27.4 from K.N.King book on C programming.
my attempt:
```
#include <stdio.h>
#include <complex.h>
#include <math.h>
int main(void)
{
int n, k;
double complex nth;
printf("Enter positive integer: ");
scanf("%d", &n);
for (k = 0; k < n; k++) {
nth = exp(2 * M_PI * I * k / n);
printf("k = %d, %g + %g\n", k, creal(nth), cimag(nth));
}
return 0;
}
```
No matter what value of n I pass results are always the same. Can you give me some tips?
|
Theexpfunction expects adouble, but you pass it adouble complex.
Usecexpinstead:
```
nth = cexp(2 * M_PI * I * k / n);
```
Output:
```
Enter positive integer: 5
k = 0, 1 + 0
k = 1, 0.309017 + 0.951057
k = 2, -0.809017 + 0.587785
k = 3, -0.809017 + -0.587785
k = 4, 0.309017 + -0.951057
```
|
I have a macro that I define at the beginning of a header and then undef at the end. However that macro (I'll call itfoo) depends on another macro (I'll call ittest). I was wondering whether I can remember the value to whichfooexpands. My first idea was the following, which obviously doesn't work:
```
#define foo test
#define bar foo
#undef foo
...
bar
...
```
Is there a way to make so that in the endbarexpands totest?
|
No, you can't.
Macros are expanded only at the moment they are inserted into the programming token stream. They are not expanded in the#definepreprocessing directive.
|
Take for instance the following example of calling a function, and assigning a value to one of its parameters at call time:
```
int MyFunction(int flag, float value);
MyFunction(myFlag=666, 3.14);
```
It's legal, though perhaps dangerous, to assign values to variables in a function call's parameter list.
How can I do something similar when a function's parameter may be a structure?
```
typedef struct
{
int i, j;
float k;
} my_struct;
int MyFunction(my_struct values);
myValues.i = 666;
myValues.k = 3.14;
MyFunction(myValues);
// how about this instead:
MyFunction({myValues.j=777}); // or something similar?
```
|
You can assign a compound literal to the variable:
```
MyFunction(myValues = (my_struct) {myValues.i, .j=777, myValues.k});
```
|
I'm trying to execute this code:
```
signal(SIGALRM,handler);
alarm(1);
while(1){}
```
Thehandlerfunction just prints "test".
alarm(1)will eventually be executed only one time in this case. I tried to put it in the loop and it seems that it doesn't get executed at all!
I am kinda new to signals. Can someone explains to me how this happens?
|
If you just putalarm(1)in the loop in your example, you'll callalarm(1)infinitely many times within a few microseconds of each invocation. And thenthishappens:
If an alarm has already been set with alarm() but has not been delivered, another call to alarm() will supersede the prior call.
I.e., the alarm gets cleared in each iteration of the loop. And since your loop runs forever, the alarm is never permanently set.
|
I have third party C library. I want to use it in c++
Every function return error code.
when i have to use it I have to write code like this:
```
int err;
err=libFun1(....);
check(err);
err=libFun2(....);
check(err);
```
I want to wrap this functions and avoid code duplication of check. Every of this librabry function have different number parameters. What will be a good design for this?
|
How about a templated function:
```
template <typename T>
int CallWrapper(T func)
{
int error = func();
check(error);
return error;
}
```
Then call it withCallWrapper(libFun1);.
|
This question already has answers here:Why must int pointer be tied to variable but not char pointer?(8 answers)Closed6 years ago.
Correct me if I am wrong, but I had assumed this line of code:
```
const char *foo = "Hello";
```
Meant that an array of chars filled with "Hello" are created somewhere on the stack, and foo is a pointer to it. In that case, I don't understand why this line of code gives an "invalid conversion from 'int' to 'const int*'
```
const int *foo = 5;
```
Won't it just create an integer of 5 somewhere on the stack and have foo point to it?
|
Because"Hello"is astring literalof typechar [N](in C) andconst char[N](in C++), which decays to a typechar*(in C) orconst char*(in C++), same as the pointer you are binding it to. On the other hand,5is a rvalue and its type is anint, so you cannot bind it to a pointer of typeconst int*.
You may findthisuseful.
|
I'm working on a webserver in UNIX environment with C language. Currently, I have done jailing the process but now I cannot use syslog and logging to a file option and that's basically due to the changed root path.
New root path for the program is it's directory. I could not escape from it to real root "/" in order to use these functions and go back to jail root path again.
Are there any other alternatives or solutions to this?
|
The whole point of usingchroot()is to make the real root inaccessible, so easy formula: If you can break it, you don't need it.
So, you should make syslog accessible from within your chroot environment instead. How? Justopenlog()prior tochroot(). After that, you cansyslog()even though you wouldn't be able toopenlog()it anymore.
|
I understand how pointers to pointers work, but I can't understandwhy using pointers to pointers over simple pointers, and when using them inC programming(not C++). I've read a lot of posts about it, but I can't found a satisfying answer. All examples I've seen can be turned into a one-level pointer solution. Can someone give an simple example where pointers to pointers are "mandatory" (that can't be done with simple pointers) ?
|
A simple is a case where you want to modify the pointer itself. For example,
```
void func(char **p)
{
*p = malloc(1024); / allocate 1024 bytes */
}
int main(void)
{
char *p = NULL;
func(&p);
/* Now, p points at memory block of 1024 bytes and do something with it */
return 0;
}
```
Of course, it's possible to do this memory allocation via another methods such as returning a pointer from the function etc. But this is one way where the pointer to pointer is useful.
|
I have third party C library. I want to use it in c++
Every function return error code.
when i have to use it I have to write code like this:
```
int err;
err=libFun1(....);
check(err);
err=libFun2(....);
check(err);
```
I want to wrap this functions and avoid code duplication of check. Every of this librabry function have different number parameters. What will be a good design for this?
|
How about a templated function:
```
template <typename T>
int CallWrapper(T func)
{
int error = func();
check(error);
return error;
}
```
Then call it withCallWrapper(libFun1);.
|
This question already has answers here:Why must int pointer be tied to variable but not char pointer?(8 answers)Closed6 years ago.
Correct me if I am wrong, but I had assumed this line of code:
```
const char *foo = "Hello";
```
Meant that an array of chars filled with "Hello" are created somewhere on the stack, and foo is a pointer to it. In that case, I don't understand why this line of code gives an "invalid conversion from 'int' to 'const int*'
```
const int *foo = 5;
```
Won't it just create an integer of 5 somewhere on the stack and have foo point to it?
|
Because"Hello"is astring literalof typechar [N](in C) andconst char[N](in C++), which decays to a typechar*(in C) orconst char*(in C++), same as the pointer you are binding it to. On the other hand,5is a rvalue and its type is anint, so you cannot bind it to a pointer of typeconst int*.
You may findthisuseful.
|
I'm working on a webserver in UNIX environment with C language. Currently, I have done jailing the process but now I cannot use syslog and logging to a file option and that's basically due to the changed root path.
New root path for the program is it's directory. I could not escape from it to real root "/" in order to use these functions and go back to jail root path again.
Are there any other alternatives or solutions to this?
|
The whole point of usingchroot()is to make the real root inaccessible, so easy formula: If you can break it, you don't need it.
So, you should make syslog accessible from within your chroot environment instead. How? Justopenlog()prior tochroot(). After that, you cansyslog()even though you wouldn't be able toopenlog()it anymore.
|
I am trying to figure out if there is a better way to test if a string being entered at the command line is a valid enum entry for a C program.
Is there a better way to test the entries in an enum instead of saying:
```
if((!strcmp(string, "NUM0")) && (!strcmp(string, "NUM1")))
{
printf("Invalid entry\n");
return(EXIT_FAILURE);
}
```
|
I do it this way:
```
enum opt {NUM0, NUM1, NUM2, OPT_END};
static const char *opt_str[OPT_END] = {"NUM0", "NUM1", "NUM2"};
enum opt i;
for (i = 0; i < OPT_END; ++i)
if (strcmp(string, opt_str[i]) == 0) break;
if (i == OPT_END) {
puts("Invalid entry");
return EXIT_FAILURE;
}
/* do something with i */
```
Additionally, you could employx-macrosto ensure your enums and strings are in sync:How to convert enum names to string in c.
|
The segmentation fault error disappears after commenting out the scanf loop. Why is that loop giving me a segmentation fault?
```
char** nameArray = malloc(numNames * sizeof(char *));
for(i =0; i< 10; i++) {
nameArray[i] = malloc(25 * sizeof(char));
}
for (i = 0; i< numNames; i++) {
scanf("%s", &nameArray[i]);
}
for (i =0; i<numNames; i++) {
free(nameArray[i]);
}
```
|
First you need to change
```
for(i =0; i< 10; i++) {
```
to
```
for(i =0; i< numNames; i++) {
```
as you need to create enough entries.
Also you need to change this line
```
scanf("%s", &nameArray[i]);
```
to
```
scanf("%s", nameArray[i]);
```
asnameArray[i]is a character pointer as required.
Also it would be better to use
```
scanf("%24s", nameArray[i]);
```
as this would prevent buffer overrun. Also it would be a good idea to check the return value of scant
|
```
void Tmr_Wait1us (uint16_t delay) {
uint16_t i;
TCNT0 = 0; // will start to count from 0 up to 255 (if 8-bit timer)
for (i = 0; i < delay / 256; i++)
while (TCNT0 < 255)
;
while (TCNT0 <= delay % 256)
;
}
```
This code is used to set a timer to wait precise amount of time, to be applied to AVR-Atmega32a , I can't understand what the empty loops does here? also what the second loop does?
|
TCNT0is the current timer count for timer 0, a 8-bit timer. Since it counts asynchronously from your code, it will increment even if the CPU is in a spin wait.
But since avr-libc provides fairly precise spin waits inutil/delay.hyou are usually better off using those instead.
```
for (int i = 0; i < delay; i++)
_delay_us(1);
```
|
I'm trying to learn more about how computers store memory. So I've found information on how to represent binary numbers or hexadecimal numbers, but I found a question asking:
```
Given three n-bit unsigned ints: x, y, z, what is the min #
of bits required to represent x * y + z
```
So my thinking is: Do I have to just account for all three ints separately and do the math for the smallest possible numbers so for example 0 * 0 + 0
Or do I have to account for another variable n that is the result of the problem?
I'm having some trouble thinking this out.
|
The number of bits required isn + n. Taking an example using 8 bits and maximum unsigned values:
```
255 * 255 + 255 = 65280
```
The result is less then65536which would require more than 16 bits.
|
I tried the following code in gcc:
```
#include<stdio.h>
int main()
{
int a=3,2,1;//////////////////////ERROR!//////////////////////////
printf("%d", a);
return 0;
}
```
I expected it to compile successfully as:
a series of integer expressions seperated by commas will be evaluated from left to right and the value of the right-most expression becomes the value of the total comma separated expression.
Then, the value of the integer variable a should have been 1 right? Or is it 3?
And why am I getting this error when I try to execute this program?
error: expected identifier or '(' before numeric constant
|
That's parsed as a three-part variable declaration, with two invalid variables.
You need to wrap the entire initializer in parentheses so that it's parsed as a single expression:
```
int a=(3,2,1);
```
|
I am trying to convertASCIIhexadecimal value (0x61 or 61) to it'scharvalue (61 = a, etc..)withoutatoi,scanf,strcat.
I am savinggetchar()to temp variable, then I save first one (6) in array, then save second one (1) in array, now i want take these two and convert them to their ASCII value.
```
68656c6c6f0d0a = hello
void asd(char fde)
{
char asmg[3];
asmg[0] = "0x";
asmg[1] = "6";
asmg[2] = "1";
printf("%c", asmg);
}
```
I expected it to print "a", but it doesn't work.
Something like that, but this doesn't work. I need to put asmg[0], [1], [2] to one char, then it should work.
Thanks :)
|
Not sure exactly what you are trying to do but this may help.
```
int main(int argc, char **argv)
{
int hex[6] = {0x68, 0x65, 0x6C, 0x6C, 0x6F};
int i = 0;
for(i = 0; i <6; i++)
{
printf("%c", hex[i]);
}
printf("\n");
}
```
|
I was recently doing some experiments with theforkfunction and I was concerned by a "simple" (short) question:
Doesforkuses concurrency or parallelism (if more than one core) mechanisms?Or, is it the OS which makes the best choice?
Thanks for your answer.
nb: Damn I fork bombed myself again!
Edit:
Concurrency: Each operation run on one core. Interrupts are received in order to switch from one process to another (Sequential computation).Parallelism: Each operation run on two cores (or more).
|
fork()duplicates the current process, creating another independent process. End of story.
How the kernel chooses to schedule these processes is a different, very broad question. In general the kernel will try to use all available resources (cores) to run as many tasks as possible. When there are more runnable tasks than cores, it has to start making decisions about who gets to run, and for how long.
|
```
void Tmr_Wait1us (uint16_t delay) {
uint16_t i;
TCNT0 = 0; // will start to count from 0 up to 255 (if 8-bit timer)
for (i = 0; i < delay / 256; i++)
while (TCNT0 < 255)
;
while (TCNT0 <= delay % 256)
;
}
```
This code is used to set a timer to wait precise amount of time, to be applied to AVR-Atmega32a , I can't understand what the empty loops does here? also what the second loop does?
|
TCNT0is the current timer count for timer 0, a 8-bit timer. Since it counts asynchronously from your code, it will increment even if the CPU is in a spin wait.
But since avr-libc provides fairly precise spin waits inutil/delay.hyou are usually better off using those instead.
```
for (int i = 0; i < delay; i++)
_delay_us(1);
```
|
I'm trying to learn more about how computers store memory. So I've found information on how to represent binary numbers or hexadecimal numbers, but I found a question asking:
```
Given three n-bit unsigned ints: x, y, z, what is the min #
of bits required to represent x * y + z
```
So my thinking is: Do I have to just account for all three ints separately and do the math for the smallest possible numbers so for example 0 * 0 + 0
Or do I have to account for another variable n that is the result of the problem?
I'm having some trouble thinking this out.
|
The number of bits required isn + n. Taking an example using 8 bits and maximum unsigned values:
```
255 * 255 + 255 = 65280
```
The result is less then65536which would require more than 16 bits.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.