question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
In the following program,Why compiler does not gives any error or warning?
```
cc -Wall -pedantic my_program.c
```
code here:
```
#include <stdio.h>
void f()
{
return; // return statement in void function
}
int main()
{
f();
return 0;
}
```
I have compiled the program inGCCcompiler onLinuxplatform.
|
Of course you can usereturn;in avoidfunction. How else would you return early from such a function?
In your case the statement is redundant as it's reached on all control paths, but a compiler will certainly not issue a diagnostic in that instance.
(Note that youmustreturnexplicitly from a non-voidfunction, with the exception ofmain(), where a compiler must generatereturn 0;if missing.
|
I opened a socket with
```
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
```
then send packet with
```
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serveraddr.sin_addr.s_addr, server->h_length);
serveraddr.sin_port = htons(portno);
sendto(sockfd, buf, strlen(buf), 0, &serveraddr, serverlen);
```
In what stage the source port of the socket is assigned ? insocket()or insendto()?
Does the source port keep unchanged in all calls ofsendto()function ?
|
sendto() perform an implicit bind if you do not call bind() explicitly.
|
This question already has answers here:Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer(5 answers)Closed6 years ago.
i tried coping a string to a pointer using strcpy. it causes a segmentation fault.any reason for that.
```
#include <stdio.h>
#include <string.h>
int main()
{
char *str=NULL;
strcpy(str,"C-DAC");
printf("%s\n",str);
return 1;
}
```
|
WHere does your string point to? Nowhere!
That's why you have segmentation fault. You have to either allocate variable on stack as array or define it as pointer and later allocate memory usingmalloc. When usingmalloc, don't forget to include "stdlib.h"
Either do this:
```
char str[6];
strcpy(str,"C-DAC");
```
or
```
char *str=malloc(sizeof(*str) * 6);
strcpy(str,"C-DAC");
```
|
Suppose that I have associated (in my mind, not as code) a status thing with an integer array of size n.int array[n] = {0,0,1,0,1,0,1,0,1,.......}. (only 0 and 1 in this array)Status '0' means 'locked' in my context. Similarly, '1' means 'unlocked'.
I want that everytime, I print the variable, e.g.int array[3], I want to output its status as a string and not the actual value of variable.
How do I do this? Is there a way I can actually replace0with "locked" and1with "unlocked"?P.S. - I DON'T want to create another array with data type string or simply putting an if-else equation. Help with macros will be much appreciated.
|
Sure, you can use string literals and decide which to use based on the value of the array slot.
```
for (int i = 0; i < n; i++) {
const char *is_locked = (array[i] == 0) ? "locked" : "unlocked";
printf("status of %d: %s\n", i, is_locked);
}
```
|
I'm trying to improve my knowledge with pointers by making an pointer who points to another pointer that is practically a string.
Now I want to get size who normally I could get fromsizeof(foo[0])/sizeof(foo[0][0])
Pointer form
```
char** foo;
```
|
sizeof(test)/sizeof(*test)doesn't indicate the number of elements anymore with your declaration, because the compiler doesn't know what is the pointer pointing to, becausesizeof()is a compile time operation and hence not dynamic.
To find no of elements, you can add a sentinel value:
```
char **test = {"New York", "Paris", "Cairo", NULL};
int testLen = -1;
while(test[++testLen] != NULL){
//DO NOTHING
}
```
|
I have a message encoded with Nanopb implementation of Google Protocol Buffers.
I have to decode it to display the decoded result on a php page.
Is it possible to do it with PHP ?
If not, what is the best solution to do it in order to get an exploitable result in php ?
Thanks for your help.
|
Use php implementation of google protocol buffers like for instance:
google/protobuf/php
protobuf-php
|
In C11,
```
char foo(char x, char y) {
return x % y;
}
```
Is any implicit conversion (e.g. promotion to int) done anywhere?
|
Usual arithmetic conversions apply to operands of%the same way they apply to operands of other multiplicative and additive operators (see6.5.5 Multiplicative operators).
The operands are promoted either tointor tounsigned int, depending on the range ofchartype on your platform (see6.3.1.8 Usual arithmetic conversionsand6.3.1.1 Boolean, characters, and integers)
On most real-life platforms, the operands will be promoted toint, since range ofinttypically covers the full range ofchar. On a more-or-less exotic platform wheresizeof(char) == sizeof(int)andcharis an unsigned type (implying that range ofchardoes not fit into range ofint), they will be promoted tounsigned int.
|
I am trying to run below program in an online C compiler. But I get segmentation error. Can you help me fix this
```
#include <stdio.h>
#include <string.h>
int main()
{
char string[15] = "Strlwr in C";
printf("%s",tolower(string));
return 0;
}
```
|
Following is the prototype oftolower
```
int tolower(int c);
```
You should pass anintor something likecharwhich can safely convert toint. Passingchar *(Type ofstring) like you do leads to UB.
To convert a string to lowercase, you need to convert each character separately. One way to do this is:
```
char string[15] = "Strlwr in C";
char lstr[15];
int i = 0;
do {
lstr[i] = tolower(string[i]);
} while(lstr[i] != '\0');
printf("%s", lstr);
```
|
I'm trying to improve my knowledge with pointers by making an pointer who points to another pointer that is practically a string.
Now I want to get size who normally I could get fromsizeof(foo[0])/sizeof(foo[0][0])
Pointer form
```
char** foo;
```
|
sizeof(test)/sizeof(*test)doesn't indicate the number of elements anymore with your declaration, because the compiler doesn't know what is the pointer pointing to, becausesizeof()is a compile time operation and hence not dynamic.
To find no of elements, you can add a sentinel value:
```
char **test = {"New York", "Paris", "Cairo", NULL};
int testLen = -1;
while(test[++testLen] != NULL){
//DO NOTHING
}
```
|
I have a message encoded with Nanopb implementation of Google Protocol Buffers.
I have to decode it to display the decoded result on a php page.
Is it possible to do it with PHP ?
If not, what is the best solution to do it in order to get an exploitable result in php ?
Thanks for your help.
|
Use php implementation of google protocol buffers like for instance:
google/protobuf/php
protobuf-php
|
In C11,
```
char foo(char x, char y) {
return x % y;
}
```
Is any implicit conversion (e.g. promotion to int) done anywhere?
|
Usual arithmetic conversions apply to operands of%the same way they apply to operands of other multiplicative and additive operators (see6.5.5 Multiplicative operators).
The operands are promoted either tointor tounsigned int, depending on the range ofchartype on your platform (see6.3.1.8 Usual arithmetic conversionsand6.3.1.1 Boolean, characters, and integers)
On most real-life platforms, the operands will be promoted toint, since range ofinttypically covers the full range ofchar. On a more-or-less exotic platform wheresizeof(char) == sizeof(int)andcharis an unsigned type (implying that range ofchardoes not fit into range ofint), they will be promoted tounsigned int.
|
I am trying to run below program in an online C compiler. But I get segmentation error. Can you help me fix this
```
#include <stdio.h>
#include <string.h>
int main()
{
char string[15] = "Strlwr in C";
printf("%s",tolower(string));
return 0;
}
```
|
Following is the prototype oftolower
```
int tolower(int c);
```
You should pass anintor something likecharwhich can safely convert toint. Passingchar *(Type ofstring) like you do leads to UB.
To convert a string to lowercase, you need to convert each character separately. One way to do this is:
```
char string[15] = "Strlwr in C";
char lstr[15];
int i = 0;
do {
lstr[i] = tolower(string[i]);
} while(lstr[i] != '\0');
printf("%s", lstr);
```
|
In theRFC1321
I notice this piece of code:
```
if ((context->count[0] += ((UINT4)inputLen << 3)) < ((UINT4)inputLen << 3))
context->count[1]++;
context->count[1] += ((UINT4)inputLen >> 29);
```
I don't understand the comparison:
```
((UINT4)inputLen << 3)) < ((UINT4)inputLen << 3))
```
It is like it always returns 0, right?
|
There is no such comparison. Look how the parentheses are paired:
It is
```
(X < ((UINT4)inputLen << 3))
```
whereX=
```
(context->count[0] += ((UINT4)inputLen << 3))
```
|
Suppose I will enter the data in this way.
```
18-MAR-1995
```
Now I want to store this one data into different variables using one single scanf() function.
Let say the variables are,
```
int dd,yy;
char month[3];
```
18 will store in dd variableMAR will store in month variable1995 will store in yy variable
I tried this one
```
scanf("%d[^-]%s[^-]%d",&dd,s,&yy);
```
IDEONE LINK HERE
|
Note thatscanfsyntax is different from regular expressions; it seems you're confusing the two. Non-special characters match themselves, so-needs no special treatment. Furthermore,%salways expects a whitespace-terminated string (word), so you need%3cto match three characters exactly.
So the correct format string is:
```
scanf("%d-%3c-%d", &dd, month, &yy);
```
Note that no terminating'\0'byte will be added tomonth! So this is well-defined behaviour, but don't try to usemonthas a null-terminated string.
|
a.h
```
struct S1{...};
extern "C" struct S1 *f();
extern "C" void freeS1(struct S1 *ptr);
```
a.cpp
```
extern "C" struct S1 *f() {
struct S1 *ptr = new struct S1();
...
return ptr;
};
extern "C" void freeS1(struct S1 *ptr) {
delete ptr;
};
```
b.c
```
struct S1 *ptr = f();
.....
freeS1(ptr);
```
|
Memory is memory, it doesn't really matter which allocator provided it, as long as it's correctly aligned and allocation and deallocation functions are correctly matched (and the structure definition is the same). There should be no problem.
|
I'm currently in the process of writing a tree enumerator where I've come across the following problem:
I'm looking at masked bitsets, i.e. bitsets where the set bits are a subset of a mask, i.e.0000101with mask1010101. What I want to accomplish is increment the bitset, but only with respect to the masked bits. In this example, the result would be0010000. To make it a bit clearer, extract only the masked bits, i.e.0011, increment them to0100and distribute them to the mask bits again, giving0010000.
Does anybody see an efficient way to do this, short of implementing the operation by hand using a combination of bitscans and prefix masks?
|
Just fill the non mask bits with ones so that they propagate carry:
```
// increments x on bits belonging to mask
x = ((x | ~mask) + 1) & mask;
```
|
I'm Trying to build a simple socket.
```
#include<stdio.h>
#include<winsock2.h>
#include<ws2tcpip.h>
int getaddrinfo(const char *node,
const char *service,
const struct addrinfo *hints,
struct addrinfo **res);
int main(int argc, char *argv[])
{
WSADATA wsa;
SOCKET a;
printf("Initializing...");
if(WSAStartup(MAKEWORD(2,2),&wsa)!=0);
printf("Failed, Error:%d",WSAGetLastError());
if((a=socket(AF_INET,SOCK_STREAM,0))==INVALID_SOCKET);
printf("Failed, Error:",WSAGetLastError());
return 0;
}
```
But getting the error "Undefined reference to..." on all winsock2 related functions(like WSAStartup).
|
Undefined reference errors mean you have not linked the socket library to your project. The header files tell it what the functions look like but the library files actually do the work. See forthis answerfor details of how to do it.
|
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
Below is the code, please pin point exactly where i am wrong.
I have declared, defined the function, i don't know what is wrong.
```
#include<stdio.h>
int factorial(int b); /* Declaration */
int main()
{
int num;
printf("Enter number: ");
scanf("%d", &num);
printf("%d",factorial(num));
return 0;
}
int factorial(int b) /*Function definition*/
{
return b*factorial(b-1);
}
```
|
You need to end the recursion at some point:
```
int factorial(int b) /*Function definition*/
{
if (b == 0) return 1;
return b*factorial(b-1);
}
```
|
I am running my C program and I want to see the memory used by this. I am using the profilergprof. Is it possible withgprof? Or maybe I have to study theValgrindprofile?
|
If you want to go down the Valgrind route, Massif is the tool to use:
valgrind --tool=massif your_app -your_options
|
How integer pointer to char pointer conversion works?
I have a program that has integer value 320 and I'm typecasting into char*. It will show the output 64. I want to know how its works?
```
#include <stdio.h>
int main()
{
int i=320;
char *p=(char*)&i;
printf("%d",*p);
return 0;
}
```
|
Well, on your little-endian system, let's assumesizeof (int)is 4.
Then the memory forilooks like:
```
+--+-+-+-+
i: |64|1|0|0|
+--+-+-+-+
```
This is because 320 is 0x00000140, i.e. 320 = 1 * 256 + 64.
So you setpto point at the first byte (64), and then dereference it so that single byte is read.
Your final line is wrong, you meant:
```
printf("%d\n", *p);
```
|
In theRFC1321
I notice this piece of code:
```
if ((context->count[0] += ((UINT4)inputLen << 3)) < ((UINT4)inputLen << 3))
context->count[1]++;
context->count[1] += ((UINT4)inputLen >> 29);
```
I don't understand the comparison:
```
((UINT4)inputLen << 3)) < ((UINT4)inputLen << 3))
```
It is like it always returns 0, right?
|
There is no such comparison. Look how the parentheses are paired:
It is
```
(X < ((UINT4)inputLen << 3))
```
whereX=
```
(context->count[0] += ((UINT4)inputLen << 3))
```
|
Suppose I will enter the data in this way.
```
18-MAR-1995
```
Now I want to store this one data into different variables using one single scanf() function.
Let say the variables are,
```
int dd,yy;
char month[3];
```
18 will store in dd variableMAR will store in month variable1995 will store in yy variable
I tried this one
```
scanf("%d[^-]%s[^-]%d",&dd,s,&yy);
```
IDEONE LINK HERE
|
Note thatscanfsyntax is different from regular expressions; it seems you're confusing the two. Non-special characters match themselves, so-needs no special treatment. Furthermore,%salways expects a whitespace-terminated string (word), so you need%3cto match three characters exactly.
So the correct format string is:
```
scanf("%d-%3c-%d", &dd, month, &yy);
```
Note that no terminating'\0'byte will be added tomonth! So this is well-defined behaviour, but don't try to usemonthas a null-terminated string.
|
a.h
```
struct S1{...};
extern "C" struct S1 *f();
extern "C" void freeS1(struct S1 *ptr);
```
a.cpp
```
extern "C" struct S1 *f() {
struct S1 *ptr = new struct S1();
...
return ptr;
};
extern "C" void freeS1(struct S1 *ptr) {
delete ptr;
};
```
b.c
```
struct S1 *ptr = f();
.....
freeS1(ptr);
```
|
Memory is memory, it doesn't really matter which allocator provided it, as long as it's correctly aligned and allocation and deallocation functions are correctly matched (and the structure definition is the same). There should be no problem.
|
I have an array (array) that contains some char that are numbers:
```
char array[] = [20, 3, 32, 34, -12] //for example
```
I want to include this numbers for calling a function in the following way:
for array[0], the message to send would be "R 20".
For array[1], it would be "R 3"...
```
sendtoserver("R 20");
```
How can I do this? I know I need a "for" loop for all of them, but my question is how do I get the "R array[0]" to be "R 20".
Thanks in advance!
|
sprintfit to a sufficiently sized buffer and pass the buffer:
```
char buf[14];
//14 is enough for "R " (2) +
//the decimal representation of any 32 bit int (11) + '\0' (1)
//2 + 4 + 1 = 7 would be enough for sized, 8 bit chars
sprintf(buf, "R %d", array[i]);
```
|
I have a 128-bit vector of 4 floats that have been calculated, and I want to change the order of this vector like so:
```
Vector A before reordering
+---+---+---+---+
| a | b | c | d |
+---+---+---+---+
Vector A after reordering
+---+---+---+---+
| b | a | c | d |
+---+---+---+---+
```
As I said the vector has been calculated by earlier computations so no way to use_mm_set_ps()... Anyone have a clue on how can it be done?
|
You're looking for theSHUFPSinstruction(shuffle packed single-precision floats).The corresponding intrinsic is_mm_shuffle_ps:
```
__m128 _mm_shuffle_ps(__m128 a, __m128 b, unsigned int imm8);
```
The third parameter, an 8-bit immediate, is the permutation. This indicates how you want the values to be shuffled. To create this readably, you'll want to use the_MM_SHUFFLEmacro. Here's a helpful graphical description of how_MM_SHUFFLEworks, taken fromsome old Microsoft documentation:
|
I am using C GTK+3, using Glade for the GUI design. I have a GtkGrid with 1 row and 3 columns. I have a button on column 2 and I want to add a spacer in column 1 and 3 so the button stays in the middle of the window.
Which GTK3 widget should I use to act as a simple 'spacer'?
|
From your description I'm assuming your interface looks like so:
I think your trying to achieve an interface like so:
Which can be achieved by changing the alignment from fill to centre in the 'Common' tab:
However if you wanted the button to be centred regardless of any content placed in Col 1 / 3 you would be better off with a GtkBox with a center widget:
Which is achieved like so:
Add a horizontally orientated GtkBox and enable center child
Add your button to the extra placeholder displayed
Set any content you want to the right of the button as pack end
|
i write code in c and i want to terminate if statement i use.
```
exit();
```
function it works but it will create new problem.
```
getch();
```
function stop working in my code and the output wont stay on screen it just flash and disappeared.
here is my code
```
#include<stdio.h>
#include<cono.h>
#include<iostream.h>
#include<stdlib.h>
void main(void)
{
int a,b;
printf("enter a");
scanf("%d",&a);
printf("enter b");
scanf("%d",&b);
if(a==1,b<=8)
{
printf("you");
exit(0);
}
if(a==2,5<b<=10)
{
printf("you");
else
printf("me");
}
getch();
}
```
|
I think you misunderstood the concept of the functionexit(int). Theexitfunction terminates the current calling process and returns control to the Operating System, which in your case means that it terminates the execution ofmain.
|
How to write "or" inside dependencies in makefile, I need to check both .c and .cpp:
```
SOURCES=$(wildcard $(SRC)/*.cpp) $(wildcard $(SRC)/*.c)
myTarget: $(SOURCES:.cpp||.c=.o)
g++ ...
```
It is not working, could you use an "or" in this situation?
|
It looks like you are using GNU make. If you are, you can use two calls of the functionsubst.
```
INTERMEDIATE=$(subst .cpp,.o,$(SOURCES))
OBJECTS=$(subst .c,.o,$(INTERMEDIATE))
myTarget:$(OBJECTS)
```
If you don't want to useINTERMEDIATE, you can use:
```
OBJECTS=$(subst .c,.o,$(subst .cpp,.o,$(SOURCES)))
```
|
I have an array (array) that contains some char that are numbers:
```
char array[] = [20, 3, 32, 34, -12] //for example
```
I want to include this numbers for calling a function in the following way:
for array[0], the message to send would be "R 20".
For array[1], it would be "R 3"...
```
sendtoserver("R 20");
```
How can I do this? I know I need a "for" loop for all of them, but my question is how do I get the "R array[0]" to be "R 20".
Thanks in advance!
|
sprintfit to a sufficiently sized buffer and pass the buffer:
```
char buf[14];
//14 is enough for "R " (2) +
//the decimal representation of any 32 bit int (11) + '\0' (1)
//2 + 4 + 1 = 7 would be enough for sized, 8 bit chars
sprintf(buf, "R %d", array[i]);
```
|
I have a 128-bit vector of 4 floats that have been calculated, and I want to change the order of this vector like so:
```
Vector A before reordering
+---+---+---+---+
| a | b | c | d |
+---+---+---+---+
Vector A after reordering
+---+---+---+---+
| b | a | c | d |
+---+---+---+---+
```
As I said the vector has been calculated by earlier computations so no way to use_mm_set_ps()... Anyone have a clue on how can it be done?
|
You're looking for theSHUFPSinstruction(shuffle packed single-precision floats).The corresponding intrinsic is_mm_shuffle_ps:
```
__m128 _mm_shuffle_ps(__m128 a, __m128 b, unsigned int imm8);
```
The third parameter, an 8-bit immediate, is the permutation. This indicates how you want the values to be shuffled. To create this readably, you'll want to use the_MM_SHUFFLEmacro. Here's a helpful graphical description of how_MM_SHUFFLEworks, taken fromsome old Microsoft documentation:
|
I am using C GTK+3, using Glade for the GUI design. I have a GtkGrid with 1 row and 3 columns. I have a button on column 2 and I want to add a spacer in column 1 and 3 so the button stays in the middle of the window.
Which GTK3 widget should I use to act as a simple 'spacer'?
|
From your description I'm assuming your interface looks like so:
I think your trying to achieve an interface like so:
Which can be achieved by changing the alignment from fill to centre in the 'Common' tab:
However if you wanted the button to be centred regardless of any content placed in Col 1 / 3 you would be better off with a GtkBox with a center widget:
Which is achieved like so:
Add a horizontally orientated GtkBox and enable center child
Add your button to the extra placeholder displayed
Set any content you want to the right of the button as pack end
|
i write code in c and i want to terminate if statement i use.
```
exit();
```
function it works but it will create new problem.
```
getch();
```
function stop working in my code and the output wont stay on screen it just flash and disappeared.
here is my code
```
#include<stdio.h>
#include<cono.h>
#include<iostream.h>
#include<stdlib.h>
void main(void)
{
int a,b;
printf("enter a");
scanf("%d",&a);
printf("enter b");
scanf("%d",&b);
if(a==1,b<=8)
{
printf("you");
exit(0);
}
if(a==2,5<b<=10)
{
printf("you");
else
printf("me");
}
getch();
}
```
|
I think you misunderstood the concept of the functionexit(int). Theexitfunction terminates the current calling process and returns control to the Operating System, which in your case means that it terminates the execution ofmain.
|
How to write "or" inside dependencies in makefile, I need to check both .c and .cpp:
```
SOURCES=$(wildcard $(SRC)/*.cpp) $(wildcard $(SRC)/*.c)
myTarget: $(SOURCES:.cpp||.c=.o)
g++ ...
```
It is not working, could you use an "or" in this situation?
|
It looks like you are using GNU make. If you are, you can use two calls of the functionsubst.
```
INTERMEDIATE=$(subst .cpp,.o,$(SOURCES))
OBJECTS=$(subst .c,.o,$(INTERMEDIATE))
myTarget:$(OBJECTS)
```
If you don't want to useINTERMEDIATE, you can use:
```
OBJECTS=$(subst .c,.o,$(subst .cpp,.o,$(SOURCES)))
```
|
This the short code, that produces adouble free or corruptionerror.
```
SDL_Surface *surface;
SDL_Surface *surface2;
surface = NULL;
surface2 = SDL_LoadBMP("someImg.bmp");
surface = surface2;
SDL_FreeSurface(surface);
SDL_FreeSurface(surface2);
```
I don't understand, why I can't free second surface before I free first.
|
Both variablessurfaceandsurface2point to the same object. You are effectively freeing twice the same object.
|
Whensscanf()or another function from thescanffamily is given a sequence of digits whose converted value exceeds the maximum value of the target integer type,
should the conversion be considered to have failed?is the behavior defined at all?
|
From the standard, 7.21.6.2p10 ((f)scanf, applies to the whole family):
… If this object does not have an appropriate type, orif the result of the conversion cannot be represented in the object, the behavior is undefined.
Looks like another reason to be very cautious with thescanffamily. ThestrtoXXfunctions have a fully defined behaviour. They returnLONG_MAXetc. for too large input and seterrno == ERANGE. So if you need exact information, tokenise the input manually and use these functions for conversion. Another benefit: better error handling.
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed6 years ago.Improve this question
I am new to c programming. Here is my code:
```
int main() {
char *loc = " E:\ ";
return 0;
}
```
The program compiles successfully with a warning.
```
<source>: In function 'int main()':
<source>:4:17: warning: unknown escape sequence: '\040'
char *loc = " E:\ ";
```
The output of the program is "E:", but it should be "E:\". Why I am missing the '\' in the output. Whats wrong in my code??
|
You need to writeE:\\instead ofE:\. This is because the\character marks the beginning of aescape sequence. Writing a\\is itself an escape sequence that just evaluates a\.
|
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed6 years ago.Improve this question
I am learning programming. I would like to know if the above usage is right or not. is this correct?
```
(void)strcpy(somevariable1, somevariable2);
```
Is this related to type casting?
|
strcpyhas the below syntax :
```
char * strcpy ( char * destination, const char * source );
```
and it returns thedestinationwhich is apointer to char. When you explicitly cast the return value to(void), you're essentially doing
```
(void)(char*)
```
you cast the return value to nothing, or you simply drop it. This can help suppress some compiler warnings especially when you're not using the return value.
|
What is the point of disabling interrupts before getting the results and clearing the Post_Bits to its original statePost_Bits &= (~Post);and testing the condition if the particular Postres = Post_Bits & Post;was seen before.
For instance, ifPost_Bitswas used on another function and you are changing it here, does clearing it inside the disabling/Enable interrupt make it thread safe?
```
BOOL Post_a_Note(Post_t Post) // Post_t is a 32bit number
{
Post_t res; //Final Result
UINT16 capture = INTDisableInterrupts();
res = Post_Bits & Post;
Post_Bits &= (~Post);
INTRestoreInterrupts(capture);
return (res != 0);
}
```
|
Disabling interrupts is a simplest method to make sure that code fragment executed by only one thread at any time.
|
I am running the following program and getting a result as 9 7, I understood why 9 is the output but I can't figure out why I'm getting 7 as output.
```
#include<stdio.h>
#define sqr(i) (i*i)
int main()
{
printf("%d %d", sqr(3), sqr(3+1));
return 0;
}
```
For the second function that issqrt(3+1)how the micro is getting expanded and how Im getting 7 output?
|
You can have the compiler or IDE preprocess the file and show you how the macro expanded.
In your casesqr(3+1)expands to(3+1*3+1). Now the precedence of C operators means that the multiplication is done before the addition. So(3+1*3+1)->(3+3+1)->(7).
You can fix this by defining your macro this way, with parentheses around the argument:
```
#define sqr(i) ((i)*(i))
```
|
I am not sure why the static code analysis tool Coverity flags:
```
CID 40172 (#1 of 1): Parse warning (PW.INCOMPATIBLE_PARAM)
1. incompatible_param: argument of type "volatile mpls_RuntimeInfo_t *" is incompatible with parameter of type "void *"
```
for this line:
```
memset(&SW_RuntimeInfo[idx],0,sizeof(mpls_RuntimeInfo_t));
```
whenSW_RuntimeInfois declared asvolatile static mpls_RuntimeInfo_t SW_RuntimeInfo[LABEL_T_CNT] = { 0 };in the global scope.Why does it raise a flag & how do I fix this?
|
It's throwing the warning because you're passing a volatile pointer to a non-volatile parameter. If you really want to just make the warning go away, just cast your argument tovoid *. But perhaps you should re-visit whether your variable should be volatile, or initialize it in a different manner.
|
As far as I understand, things like++i++are not allowed in C/C++ because they break a rule that variables cannot be written to multiple times in a single statement. The result is undefined behaviour.
Could someone confirm if this also applies to my statement:++i %= j?
I would like a for loop where I incrementiaround a circular buffer (sizej) starting at an arbitrary pointpuntil I get back to pointp.
```
for(int i = p+1 ; i != p; ++i %= j )
{
if (buffer[i].ready())
{
buffer[i].do_something();
p = i;
break;
}
}
```
I could do it in more lines of code, but would rather not.
|
In your code you say++i % j, which means 'Increment i (and store the new value in i), then calculate the modulo of i and j. But that value is not stored anywhere.
To get a wrap around loop, you can usei = (i+1)%j
|
What is the point of disabling interrupts before getting the results and clearing the Post_Bits to its original statePost_Bits &= (~Post);and testing the condition if the particular Postres = Post_Bits & Post;was seen before.
For instance, ifPost_Bitswas used on another function and you are changing it here, does clearing it inside the disabling/Enable interrupt make it thread safe?
```
BOOL Post_a_Note(Post_t Post) // Post_t is a 32bit number
{
Post_t res; //Final Result
UINT16 capture = INTDisableInterrupts();
res = Post_Bits & Post;
Post_Bits &= (~Post);
INTRestoreInterrupts(capture);
return (res != 0);
}
```
|
Disabling interrupts is a simplest method to make sure that code fragment executed by only one thread at any time.
|
I am running the following program and getting a result as 9 7, I understood why 9 is the output but I can't figure out why I'm getting 7 as output.
```
#include<stdio.h>
#define sqr(i) (i*i)
int main()
{
printf("%d %d", sqr(3), sqr(3+1));
return 0;
}
```
For the second function that issqrt(3+1)how the micro is getting expanded and how Im getting 7 output?
|
You can have the compiler or IDE preprocess the file and show you how the macro expanded.
In your casesqr(3+1)expands to(3+1*3+1). Now the precedence of C operators means that the multiplication is done before the addition. So(3+1*3+1)->(3+3+1)->(7).
You can fix this by defining your macro this way, with parentheses around the argument:
```
#define sqr(i) ((i)*(i))
```
|
I have missing header files likemalloc.handconio.hin my MAC.
How do I install it?
gcc linkedlistmenu.c
linkedlistmenu.c:2:19: fatal error: malloc.h: No such file or directory
|
First off,malloc.his deprecated (and not available on your system). Instead, you should be usingstdlib.h. Furthermore,conio.his an implementation specific header - and in this case, it is Windows and MS-DOS specific. It is not available on MacOS. Both of these are non-standard headers, and therefore are not preferred due to issues with portability.ncurses(which should already be available on MacOS) provides similar functionality toconio.h; see if that has what you're looking for.
However, your best shot if youreallyneed these header files is to install a virtualization program such asVirtualBox, install Windows, and work from there.
|
The following code has a flaw somewhere and when reaching the 11/12/13 number entering, I get anAborted(core dumped)alert. What is wrong?
```
#include <stdio.h>
#include <stdlib.h>
int main(){
// sum nums until EOF
int* array; // pointer to the first element
int size = 10; // memory for 10 elements
int i = 0, sum = 0;
array = malloc(sizeof(int)*10); //get memory
while(scanf("%d",(array + i))!= EOF){ //read until EOF
//add element to the sum
sum += *(array+i);
//realloc memory
if(i == size-1){
size *= 2;
array = realloc(array, size);
}
i++;
}
free(array); //free the memory
printf("%d\n\n",sum); //print sum
return 0;
}
```
|
Fixed it! The realloc should have size*sizeof(int).
|
This question already has answers here:How to compile for Windows on Linux with gcc/g++?(7 answers)Closed6 years ago.
I am using Linux/GNU GCC to compile C source code. Is there any way I can generate.exefiles for Windows running on x86 or x64 architecture? The compiled code needs to be generated on the Linux machine.
|
You would need a cross-compiler to create a Windows executable in Linux.
Mingw-w64 is an advancement of the original mingw.org project, created to support the GCC compiler on Windows systems.
Installing the cross-compilation
```
sudo apt-get install mingw-w64
```
32bit
```
i686-w64-mingw32-gcc -o test.exe test.c
```
64bit
```
x86_64-w64-mingw32-gcc -o test.exe test.c
```
|
I am trying to include a header file input by user at run time.
```
int main(){
char *p;
scanf("%s",p);
#include p
#define PATH path
#include PATH
}
```
Both the methods to include a header file are not working.Is there any way to include a header file input by user at run time?
|
You cannot include any header dynamically in C language because#includebeing evaluated during compile time only(Preprocessor directivesactually happens before compilation). You need to include the header statically with#include <your_header_file.h>or#include "your_header_file.h".
|
I just started my C programming class today and I am having a problem with the output on my terminal which the C doesn't print on it's own line.
```
#include <stdio.h>
int main(){
printf("Hello World");
return 0;
```
}
|
Use a newline character, represented as'\n'. The slash is an escape character for a few special characters, such as tab'\t', and carriage return'\r'.
printf("Hello World\n");
|
I just started my C programming class today and I am having a problem with the output on my terminal which the C doesn't print on it's own line.
```
#include <stdio.h>
int main(){
printf("Hello World");
return 0;
```
}
|
Use a newline character, represented as'\n'. The slash is an escape character for a few special characters, such as tab'\t', and carriage return'\r'.
printf("Hello World\n");
|
I have a function that returns a float number:
```
float function(enum value)
```
I then have an enum
```
typedef enum
{
a = 0,
b,
c
} myenum;
```
I want to do the following:
```
function(a+1);
```
And I wonder if there are any risksother than the risk of unexpected behaviour if the enum changes. My question might seem dumb but I have to make sure that there are no risks of what I'm doing.
Please don't ask questions on why it's done like this. Because I don't know. I just need to know if it's safe or not.
|
This is safe. Moreover, the standard guarantees thata+1isbanda+2iscin the scenario that you describe:
C99 standard, section 6.7.2.2, part 3:If the first enumerator has no=, the value of its enumeration constant is0. Each subsequent enumerator with no=defines its enumeration constant as the value of the constant expression obtained by adding1to the value of the previous enumeration constant.
|
I encountered this unexpected output with the following code in which I was verifying the maximum values (represented in decimal form) of the unsigned forms of short and int types when all their bits were set to 1.
```
#include <stdio.h>
int main()
{
unsigned int n1 = 0xFFFFFFFF;
unsigned short n2 = 0xFFFF;
printf("\nMax int = %+d", n1);
printf("\nMax short = %+d", n2);
return 0;
}
```
The output I get is (compiled using the Visual Studio 2017 C/C++ Compiler):
```
Max int = -1
Max short = +65535
```
Along the lines of unsigned short, I was expecting the maximum value of the unsigned int to be +4294967295. Why isn't it so?
|
You need to use%ufor the format specifier for anunsignedtype.
|
I want to write a kernel module which reads out a register, (return value is saved in anunsigned int) and then read the the bits 16 to 22 from this variable and the convert it to an integer number. The conversion is no problem. But getting the bits out in the first place is the problem.
As example I have this 2 values in hex:
```
0x88290000d
0x005a0a00d
```
and from this 2 values I want the bits 16 to 22 as integer, any ideas how I can implement that in my kernel module ?
|
Here is how you extract bits 16 through 22, inclusive (7 bits):
Read the number from the register intounsigned int reg = ...Shiftregto the right by 16, so bit 16 is at the least significant position:reg >>= 16Mask the number with 00000000011111112, which is 0x7F:reg &= 0x7F
Note:The above counts bits starting from zero (the traditional way of numbering bits).
|
This question already has answers here:What is the full "for" loop syntax in C?(7 answers)Closed6 years ago.
My question is simple,thus I will not go in deep
can we usefor()loop without condition like this
```
for(;;space+=1)
{
printf(" ");
break;
}
```
|
Of course you can. An empty condition is taken to evaluate to1.
for (;;){/*ToDo - your code here*/}is idiomatic C.
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed6 years ago.Improve this question
I recently started coding in c. I was wondering how you can repeat/loop a task as many times as the user wants (by input).
```
int a,i;
scanf("%d", a);
for(i=0; i<a; i++){...}
```
This is the code I came up with, but it doesn't work. It's an infinite loop.
|
You need a & to scan into.
```
int a,i;
scanf("%d", &a);
for(i=0; i<a; i++){...}
```
Read a bit more about scanning integers here.
How to scanf only integer?
|
I want to change the contents of the char pointer after allocating dynamic memory, is it possible? If not, why? My program throws a run-time error.
```
#include <stdio.h>
int main()
{
char * str = (char *) malloc (10 * sizeof(char));
str = "Hello";
str[2] = 'L'; // here the program throws run time error
printf("%s", str);
return 0;
}
```
|
When pointingstr = "Hello";you didn't copy the"Hello"into the address pointed bystr. Instead, you pointedstrto string literal, and modifying it is UB -> run-time-error.
If you want to copy the content of a stringHellotostrusestrcpy.
As noted by @LethalProgrammer: usingchar[10]instead ofchar*would allow you modifying the content
|
My code is here
```
int main()
{
int a=300;
char *p=(char *)&a;
printf("%d\n",*p);
printf("%d",*++p);
}
```
output is
441
can any body explain it.
|
As we know size of int data type is2 bytesor4 bytesdepend on your system. Whilecharpointer point one byte at a time.
Memory representation ofint a = 300;
So,charpointerppointing to only first byte as show above figure.
So, first time print44output.
Then,
```
printf("%d",*++p);
```
firstpis increment and pointer point to next(second) byte. So, next byte output is1.
|
If I use uninitialized global variable in C program, What happens? Is it undefined behavior?
```
#include <stdio.h>
int i;
int main()
{
while(i < 5)
{
i++;
}
printf("%d\n", i);
return 0;
}
```
|
Is it undefined behavior?
No.
What happens?
ihas static storage duration (file scope). It will initialize to zero by default.
|
This question already has answers here:sscanf in Python(9 answers)How do I read from stdin?(25 answers)Closed7 months ago.
I am trying to solve problems from SPOJ. I need to be able to read input from stdin for that, I did a lot of problems in C using scanf but wanted to try Python as well. How do i read the stdin inputs in Python? (wanna use Python 2.6/2.7)
|
In Python 2.7
To get integers or floats as inputs you can use the key word 'input'
Example: temp=input("Give your value")
Here temp only takes a float or intThere is another command raw_input() any value that raw input is given it converts it to string and assigns the value
Example:temp=raw_input("Give your value")
Here temp is of string type
|
I'm trying to compile a program with the mbed CLI using the following command:
```
mbed compile -m UBLOX_C027 -t ARM
```
It results in the following error:
```
make.py: error: Could not find executable for ARM.
Currently set search path: No path set
```
How can I set the executable?
|
I know I am way too late but still if anyone is facing the same problem.
I solved it in this way in MAC OS.
Download GCC_ARM for MAC OS from here:https://developer.arm.com/open-source/gnu-toolchain/gnu-rm/downloadsExtract it in some location and set the path using mbed cli:
mbed config -G GCC_ARM_PATH "/Users/amod-mac/Desktop/gcc-arm-none-eabi-7-2017-q4-major/bin"
|
Im trying to create a module for the linux redhat 2.4.18
as a part of a homework assignment of mine.
and Ive got this part of code at the start of my code:
```
char* filepath;
MODULE_PARAM(filepath,"s");
```
when I compile my code with the makefile ive created im getting:
intercept.c:22: parse error before string constant intercept.c:22:
warning: type defaults to 'int' in declaration of `MODULE_PARAM'
intercept.c:22: warning: data definition has no type or storage class
where line 22 is this line:
```
MODULE_PARAM(filepath,"s");
```
P.S. Ive included: linux\module.h
|
There's a typo in the macro name:
The right syntax isMODULE_PARM(filepath, "s");
Some documentation can be found onhttp://www.tldp.org:Passing Command Line Arguments to a Modulel)
|
Why the following program gives an error?
```
#include <stdio.h>
int main()
{
unsigned int64_t i = 12;
printf("%lld\n", i);
return 0;
}
```
Error:
```
In function 'main':
5:19: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'i'
unsigned int64_t i = 12;
^
5:19: error: 'i' undeclared (first use in this function)
5:19: note: each undeclared identifier is reported only once for each function it appears in
```
But, If I remove theunsignedkeyword, it's working fine. So,Whyunsigned int64_t igives an error?
|
You cannot apply theunsignedmodifier on the typeint64_t. It only works onchar,short,int,long, andlong long.
You probably want to useuint64_twhich is the unsigned counterpart ofint64_t.
Also note thatint64_tet al. are defined in the headerstdint.h, which you should include if you want to use these types.
|
I'm trying to build this Service in Ubuntu:http://openscep.othello.ch/download/openscep-0.4.2.tar.gz.
I called:./configureand it worked as expected.
Next I calledmake all -j4there it says:
```
gcc -DHAVE_CONFIG_H -I. -I. -I../include -I../libltdl -I../include -I/usr/local/ssl/include -DOPENSCEPDIR=\"/usr/local/lib/openscep\" -g -O2 -c init.c -fPIC -DPIC -o .libs/init.lo
In file included from ../include/init.h:13:0,
from init.c:9:
../include/scep.h:84:2: error: unknown type name 'LHASH'
LHASH *conf;
^
```
I found the solution: just replaced LHASH with _LHASH and I got further.
Now I have the problem that this code relies on#include <openssl/asn1_mac.h>which is obsolete.
I miss many function with prefix:M_ASN1_I2D_can some one tell me if they have just moved, or are there new methods which have the same functionality?
|
As Suggested by @jww i installed OpenSSL 1.0.2 rather than OpenSSL 1.1.0.
|
I always thought that in C,intstands forsigned int; but I have heard that this behavior is platform specific and in some platforms,intisunsignedby default. Is it true? What says the standard, and has it evolved over time?
|
You are quite right. As perC11(the latestcstandard), chapter §6.7.2
int,signed, orsigned int
is categorized as sametype(type specifiers, to be exact). So,intis the same assigned int.
Also, re-iterating the same, from chapter §6.2.5/P4
There are fivestandard signed integer types, designated assigned char,short
int,int,long int, andlong long int. (These and other types may be
designated in several additional ways, as described in 6.7.2.) [....]
So, for any conforming environment,intstands forsigned intand vice versa.
|
Why the following program gives an error?
```
#include <stdio.h>
int main()
{
unsigned int64_t i = 12;
printf("%lld\n", i);
return 0;
}
```
Error:
```
In function 'main':
5:19: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'i'
unsigned int64_t i = 12;
^
5:19: error: 'i' undeclared (first use in this function)
5:19: note: each undeclared identifier is reported only once for each function it appears in
```
But, If I remove theunsignedkeyword, it's working fine. So,Whyunsigned int64_t igives an error?
|
You cannot apply theunsignedmodifier on the typeint64_t. It only works onchar,short,int,long, andlong long.
You probably want to useuint64_twhich is the unsigned counterpart ofint64_t.
Also note thatint64_tet al. are defined in the headerstdint.h, which you should include if you want to use these types.
|
I'm trying to build this Service in Ubuntu:http://openscep.othello.ch/download/openscep-0.4.2.tar.gz.
I called:./configureand it worked as expected.
Next I calledmake all -j4there it says:
```
gcc -DHAVE_CONFIG_H -I. -I. -I../include -I../libltdl -I../include -I/usr/local/ssl/include -DOPENSCEPDIR=\"/usr/local/lib/openscep\" -g -O2 -c init.c -fPIC -DPIC -o .libs/init.lo
In file included from ../include/init.h:13:0,
from init.c:9:
../include/scep.h:84:2: error: unknown type name 'LHASH'
LHASH *conf;
^
```
I found the solution: just replaced LHASH with _LHASH and I got further.
Now I have the problem that this code relies on#include <openssl/asn1_mac.h>which is obsolete.
I miss many function with prefix:M_ASN1_I2D_can some one tell me if they have just moved, or are there new methods which have the same functionality?
|
As Suggested by @jww i installed OpenSSL 1.0.2 rather than OpenSSL 1.1.0.
|
I always thought that in C,intstands forsigned int; but I have heard that this behavior is platform specific and in some platforms,intisunsignedby default. Is it true? What says the standard, and has it evolved over time?
|
You are quite right. As perC11(the latestcstandard), chapter §6.7.2
int,signed, orsigned int
is categorized as sametype(type specifiers, to be exact). So,intis the same assigned int.
Also, re-iterating the same, from chapter §6.2.5/P4
There are fivestandard signed integer types, designated assigned char,short
int,int,long int, andlong long int. (These and other types may be
designated in several additional ways, as described in 6.7.2.) [....]
So, for any conforming environment,intstands forsigned intand vice versa.
|
```
typedef unsigned char byte;
unsigned int nines = 999;
byte * ptr = (byte *) &nines;
printf ("%x\n",nines);
printf ("%x\n",nines * 0x10);
printf ("%d\n",ptr[0]);
printf ("%d\n",ptr[1]);
printf ("%d\n",ptr[2]);
printf ("%d\n",ptr[3]);
```
Output:
```
3e7
3e70
231
3
0
0
```
I know the first two are just hexadecimal representations of 999 and 999*16. What do the remaining 4 mean? the ptr[0] to ptr[3]?
|
Most likely you are running this on a 32 bit LE system999in hex is:-00 00 03 E7- The way it would be stored in memory would beE7 03 00 00Hence:-
ptr[0]points to the byte containingE7which is 231 in decimalptr[1]points to the byte containing03which is 3 in decimalptr[2]points to the byte containing00which is 0 in decimalptr[3]points to the byte containing00which is 0 in decimal
HTH!
|
.hfile with header for creating a list inc:
```
#ifndef SO605_GC
#define SO605_GC
#include <stddef.h>
#define MEMSIZE 4096*1024*1024
typedef struct free_node {
size_t size;
struct free_node *next;
} free_node_t;
typedef *free_node_t mem_free_t;
void *aloca(size_t size);
void libera(void *ptr);
#endif
```
When I compile the error occurs:
aloca.h:14:10: error: expected identifier or ‘(’ before ‘free_node_t’
typedef *free_node_t mem_free_t;
How to solve this?
|
You have a syntax error in
```
typedef *free_node_t mem_free_t;
```
which should be
```
typedef free_node_t *mem_free_t;
```
but please do nottypedefpointers. Also I believe that the suffix_tis typically reserved.
Note too that4096*1024*1024will not fit a 32-bit variable, whatever it is for, and probably will not multiply as you think it will.
|
Why does casting a double 728.3 to an unsigned char produce zero? 728 is 0x2D8, so shouldn'twbe0xD8(216)?
```
int w = (unsigned char)728.3;
int x = (int)728.3;
int y = (int)(unsigned char)728.3;
int z = (unsigned char)(int)728.3;
printf( "%i %i %i %i", w, x, y, z );
// prints 0 728 0 216
```
|
From the C standard 6.3.1.4p1:
When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero).If the value of the integral part cannot be represented by the integer type, the behavior is undefined.
So, unless you have >=10 bitunsigned char, your code invokesundefined behaviour.
Note that the cast explicitly tells the compiler you know what you are doing, thus suppresses a warning.
|
Why does casting a double 728.3 to an unsigned char produce zero? 728 is 0x2D8, so shouldn'twbe0xD8(216)?
```
int w = (unsigned char)728.3;
int x = (int)728.3;
int y = (int)(unsigned char)728.3;
int z = (unsigned char)(int)728.3;
printf( "%i %i %i %i", w, x, y, z );
// prints 0 728 0 216
```
|
From the C standard 6.3.1.4p1:
When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero).If the value of the integral part cannot be represented by the integer type, the behavior is undefined.
So, unless you have >=10 bitunsigned char, your code invokesundefined behaviour.
Note that the cast explicitly tells the compiler you know what you are doing, thus suppresses a warning.
|
I have defined functionAinmain.cfile. I have created three libraries which use the functionAwithout importing anything. The code works but I have only one warning:implicit declaration of function 'A' [-Wimplicit-function-declaration].
How is it possible that the functionAworks in a functionBdefined in a separate file without importing it?
How is it possible that I have only one warning when functionAis called by other functions except functionB?
|
Global non-static symbols (variablesandfunctions) have by defaultexternallinkagemeaning they can be accessed from othertranslation units.
|
I need to do this (does not round, floor or ceil):
example:
1.58700023 (16bits)
expected 1.58700000
i am doing this operation: (value-32768.0)/32768 to convert to (byte value to real value in float) int his conversion have this error = X.00000023 or others
|
It's quite possible that you cannot do this with floats; note that not all values are exactly representable as afloat: it's limited to 32 (typically) bits after all.
Forprinting, you should be able to use:
```
printf("%.3f", 1.58700023);
```
This will print1.587by rounding as the value is converted to string.
|
I'm trying to run a simple code that includes thefftwlibrary. I know the code is right as it is provided as a test code by the authors. This is what I typed during compilation:
```
gcc my file.c -L/home/ankit/Desktop/fftw-3.3.6-pl2/lib/
-I/home/ankit/Desktop/fftw-3.3.6-pl2/include/ -lfftw -lm
```
I get the errors:
myfile.c: (.Text+0x2c):. undefined reference to 'fftw_plan_dft_2d'
collect2: ld returned 1 exit status
|
It wasn't a linking problem, installation was faulty and I had to use 'sudo make install' to get the permission for the installation to be successful. I could link it with 'gcc test.c -lfftw3 -lm' after. Thanks for your suggestions!
|
This is what I'm trying to do:-
```
double x = 4.0
double y = 4.0
x+y = 8.0
```
The input has to be of double type only (given condition of the problem).
|
```
printf("%.1lf", yournumber);
```
will do the trick. This will print value to1decimal place. In case number is1.123, printed number will be rounded, in this case to1.1.
|
I am currently running this character counting .c but the EOF is not reached unless I press control D, which is very annoying.
```
#include <stdio.h>
main () {
long nc;
nc = 0;
while (getchar() != EOF) {
++nc;
}
printf("%ld\n", nc);
}
```
|
What you are seeing is the expected behavior.
EOF is encounteredonlywhen the input stream ends. What you are doing (I suppose) is press the enter key. That doesn't signal EOF, because you could type in more stuff after the enter. Ctr+D signals the end of a file.
What you can do is look for End Of Line.
And you also need to look for EOF since the user can terminate by pressing Ctr+D
(as suggested by @DavidC.Rankin)
This can be done by matching getchar() with'\n'and EOF as
```
int c
while ((c = getchar()) != '\n' && c != EOF) {
++nc;
}
```
Hope this helps.
|
This question already has answers here:Execution time of C program(18 answers)Closed6 years ago.
```
int i=0;
while(i<=100)
{
printf("hello world....\n");
i++;
}
```
For the above program, how can I find the total time of execution ofwhileloop.
|
In header file time.h have that function. you can use that.
You can see there is a clock_t variable called start which calls a clock() function.
try this:
```
clock_t start = clock();
for ( i = 0; i < 100; i++ )
rand();
printf ( "%f\n", ( (double)clock() - start ) / CLOCKS_PER_SEC );
```
it will give you execution time. for this check your conditioj in while loop. it should "< 100" i think. check this code it will work for you.
|
I want to know the size allocated by malloc.I have written the source code below.
test.c
```
#include <stdio.h>
#include <stdint.h>
#include <malloc.h>
void main(void)
{
uint8_t *test;
test = (uint8_t *)malloc(sizeof(uint8_t)*4);
printf("sizeof(test) = %d\n",malloc_usable_size(test));
free(test);
}
```
I expected size to be 4.But the result is 12.
```
sizeof(test) = 12
```
Can you tell me what's wrong?I hope that size 4 correctly comes out.
|
```
malloc_usable_size(test)
```
The value returned by above function is not fixed as you requested. it may be greater than the requested size of the allocation depending upon the cpu byte ordering and alignment. this is totally depend upon the underlaying implementation.
|
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 want to host a cpp service as a executable file and able to track the log, handle the exception and able to handle high load.
|
You can try c-sevice-interfacehttps://github.com/Taymindis/c-service-interface
This is a small bridge engine which can handle high load of request, any segfault will not break the engine, it will catch and free the thread, it is built on top NGINX, FCGI. You can setup the proxy, load balance, authentication via NGINX before reach to your interface.
The link shown as below is a wiki to Guide you how to startup from scratch.
https://github.com/Taymindis/fcgi-function/wiki/How-to-build-a-cpp-service-on-c-service-interface
|
I have the following code:
```
int vals = 0b000000000000000000;
void setBit(int num, int x, int n) {
num ^= (-x ^ num) & (1 << n);
}
int main() {
setBit(vals, 0, 1);
printf("%i\n", vals);
}
```
But, thesetBit()function does not write tovals! Theprintf()prints 0, but it should print 1 (valsis0b000000000000000001). Why?
|
You make a copy ofvalswhen you pass it in since you don't pass a pointer. Instead of trying to modify the argument, just return the modified value :
```
int vals = 0b000000000000000000;
int setBit(int num, int x, int n) {
num ^= (-x ^ num) & (1 << n);
return num;
}
int main() {
vals = setBit(vals, 0, 1);
printf("%i\n", vals);
}
```
Try not to unnecessarily modify arguments. It arguably hurts readability. Prefer returning whenever possible.
|
At the moment when Create returns I don't have the new error code.
```
typedef union {
u8* ErrorCode_u16;
} Param;
void Create(void* params)
{
Param *parameters = (Param*)params;
parameters[1].ErrorCode_u16 = Foo();
}
```
When Create return I would like to have the new error code in my array of void pointers.
Just to mention
How can I do it ?
|
Do it like this
```
Param data[2/* or more */];
Create(data);
/* data[1] has the result of Foo() call */
```
|
I am developing a small app in c using turbo c++ IDE.
I defined required constants in header file and included in the source with include directive.
I created a project by adding source file.
But while debugging,when i add a header file constant to watch window,it is showing 'undefined symbol'.
Can anyone point me in right direction?
Thanks in advance.
|
Phase 4 of the compilation processeffectively removes any#define
```
#define FOO 42
/* ... */
int a = FOO;
```
after phase 4 becomes
```
/* ... comment deleted in phase 3 */
int a = 42;
```
There is noFOOsymbol in the produced executable.
|
Im currently working on linux. Im given a task to code in C using libuvc to stream a video from a USB camera to the window using GTK. I'm getting the out from the uvc_frame_t but I have a problem in streaming it in gtk window. Can someone help?
|
Usegdk_pixbuf_new_from_datato convert the data fromuvc_any2rgbinto aGdkPixbuf. A basic GTK UI would be aGtkWindowwith aGtkImagein it.
To update the image, callgtk_image_set_from_pixbufwith a fresh new pixbuf you created. Don't forget to either reuse the pixbuf or destroy it after use, otherwise you'll face some massive memory leak. Oh, and you'll have to handle the framerate by yourself, and use a GLib event source to be notified when a new image is available fromlibuvc.
|
I am building Morton number for spatial indexing, I have 8 unsigned 16 bit numbers that will turn into __int128 number. The efficiency is crucial, so naive solution (loop over everything) or building separate 8 128bit numbers is too expensive.
I am using GCC, the target machine is 64 bits but without BMI2 support.
How can I speed up the computation?
|
If your machine is x86 and supports SSE2, there is a clever answer usingmovmskinstructions. GoogleSSE2 bit matrix transposefor full code.
|
I have a problem when callingEVP_get_cipherbynameon macOS:
```
const char *cipher_str = "aes-256-cbc";
const evp_cipher_st *cipher1 = EVP_aes_256_cbc();
const evp_cipher_st *cipher2 = EVP_get_cipherbyname(cipher_str);
```
In the code above,cipher1will always be set to a validevp_cipher_st *object, andcipher2will always be null. I haven't found a single instance ofcipher_strthat produces a non-nullcipher2.
Am I doing something wrong? Are there some other calls I should be making to get this to work?
|
You need to initialize the OpenSSL library first. If you just use libcrypto,
call:
```
OpenSSL_add_all_algorithms();
```
Refer tohttps://wiki.openssl.org/index.php/Library_Initializationfor how to handle other situations or openssl versions.
|
What does string
```
#define RCC ((RCC_TypeDef *) RCC_BASE)
```
mean?
I understand that that is a pointer's definition and RCC_BASE stands for uint_32 0x400021000 according to following lines
```
#define RCC_BASE (AHB1PERIPH_BASE + 0x00001000)
#define AHB1PERIPH_BASE (PERIPH_BASE + 0x00020000)
#define PERIPH_BASE ((uint32_t)0x40000000)
```
But why does the definition have two types: RCC_TypeDef * and uint_32?
|
```
#define RCC ((RCC_TypeDef *) RCC_BASE)
```
means macro which is of typeRCC_TypeDef *andpointsto addressRCC_BASEin MCU address space.
RCC_BASEis address where RCC registers are in MCU address space.
Address itself is number therefore it has(uint32_t)infront.
This type of macro allows you to use registers with pointer access
```
//Read RCC register APB1ENR
uint32_t apb1enr_Reg = RCC->APB1ENR;
```
|
I am basically coding in c.
I have a character pointer that points to a character. Is there an way to store this character pointed to by the character pointer in a string variable??
Because when I tried doing so using "strcpy" I got type mismatch error , because I am trying to store a character as a string in a string variable.
|
Say your pointer to character is s defined as
```
char *s;
```
You want to make it into a string.
```
char string[2];
string[0] = *s;
string[1] = '\0';
```
And you are set.
This will cause the string to have an automatic storage duration. You can choose to make it heap allocated or global scoped depending on your requirement. That I guess you already know.
|
Is there any way to create a new process which shares your file descriptor table even after an exec?clone(CLONE_FILES)won't work, as the man page says:
If a process sharing a file descriptor table calls execve(2), its file descriptor table is duplicated (unshared).
|
This can be done by injecting into the child process a custom piece of code responsible for the receival of FDs and updating the child's descriptor table.
Child process should create AF_UNIX socket and recvmsg() on it, while parent process should duplicate and "stream down" the required file descriptors using sendmsg() - seehere
|
My code can be found on my github:https://github.com/chrismunley/ParallelProgramming/tree/master
The error I get is:
PGC-W-0095-Type cast required for this conversion (my_laplace.c: 112)
PGC-W-0095-Type cast required for this conversion (my_laplace.c: 120)
PGC/x86-64 Linux 17.5-0: compilation completed with warnings
Anyone know what I am doing wrong with the Irecv? I think it has to do with the parameters. Thanks a lot!
|
This is a compiler warning indicating that it's needed to implicitly cast a data type to another that is potentially unsafe. In this case, it appears that you're passing in a reference to a MPI_Status variable to MPI_Irecv, where MPI_Irecv is expecting a reference to a MPI_Request variable.
|
I have a problem when callingEVP_get_cipherbynameon macOS:
```
const char *cipher_str = "aes-256-cbc";
const evp_cipher_st *cipher1 = EVP_aes_256_cbc();
const evp_cipher_st *cipher2 = EVP_get_cipherbyname(cipher_str);
```
In the code above,cipher1will always be set to a validevp_cipher_st *object, andcipher2will always be null. I haven't found a single instance ofcipher_strthat produces a non-nullcipher2.
Am I doing something wrong? Are there some other calls I should be making to get this to work?
|
You need to initialize the OpenSSL library first. If you just use libcrypto,
call:
```
OpenSSL_add_all_algorithms();
```
Refer tohttps://wiki.openssl.org/index.php/Library_Initializationfor how to handle other situations or openssl versions.
|
What does string
```
#define RCC ((RCC_TypeDef *) RCC_BASE)
```
mean?
I understand that that is a pointer's definition and RCC_BASE stands for uint_32 0x400021000 according to following lines
```
#define RCC_BASE (AHB1PERIPH_BASE + 0x00001000)
#define AHB1PERIPH_BASE (PERIPH_BASE + 0x00020000)
#define PERIPH_BASE ((uint32_t)0x40000000)
```
But why does the definition have two types: RCC_TypeDef * and uint_32?
|
```
#define RCC ((RCC_TypeDef *) RCC_BASE)
```
means macro which is of typeRCC_TypeDef *andpointsto addressRCC_BASEin MCU address space.
RCC_BASEis address where RCC registers are in MCU address space.
Address itself is number therefore it has(uint32_t)infront.
This type of macro allows you to use registers with pointer access
```
//Read RCC register APB1ENR
uint32_t apb1enr_Reg = RCC->APB1ENR;
```
|
I am basically coding in c.
I have a character pointer that points to a character. Is there an way to store this character pointed to by the character pointer in a string variable??
Because when I tried doing so using "strcpy" I got type mismatch error , because I am trying to store a character as a string in a string variable.
|
Say your pointer to character is s defined as
```
char *s;
```
You want to make it into a string.
```
char string[2];
string[0] = *s;
string[1] = '\0';
```
And you are set.
This will cause the string to have an automatic storage duration. You can choose to make it heap allocated or global scoped depending on your requirement. That I guess you already know.
|
Is there any way to create a new process which shares your file descriptor table even after an exec?clone(CLONE_FILES)won't work, as the man page says:
If a process sharing a file descriptor table calls execve(2), its file descriptor table is duplicated (unshared).
|
This can be done by injecting into the child process a custom piece of code responsible for the receival of FDs and updating the child's descriptor table.
Child process should create AF_UNIX socket and recvmsg() on it, while parent process should duplicate and "stream down" the required file descriptors using sendmsg() - seehere
|
My code can be found on my github:https://github.com/chrismunley/ParallelProgramming/tree/master
The error I get is:
PGC-W-0095-Type cast required for this conversion (my_laplace.c: 112)
PGC-W-0095-Type cast required for this conversion (my_laplace.c: 120)
PGC/x86-64 Linux 17.5-0: compilation completed with warnings
Anyone know what I am doing wrong with the Irecv? I think it has to do with the parameters. Thanks a lot!
|
This is a compiler warning indicating that it's needed to implicitly cast a data type to another that is potentially unsafe. In this case, it appears that you're passing in a reference to a MPI_Status variable to MPI_Irecv, where MPI_Irecv is expecting a reference to a MPI_Request variable.
|
how can i prevent or bypass the garbage valus malloc puts in my variable?
attached the code and the output!
thanks!
```
#include <stdio.h>
#include "stdlib.h"
#include <string.h>
int main() {
char* hour_char = "13";
char* day_char = "0";
char* time = malloc(strlen(hour_char)+strlen(day_char)+2);
time = strcat(time,day_char);
time = strcat(time,"-");
time = strcat(time,hour_char);
printf("%s",time);
free(time);
}
```
this is the output i get:
```
á[┼0-13
```
|
The firststrcatis incorrect, becausemalloc-ed memory is uninitialized. Rather than usingstrcatfor the first write, usestrcpy. It makes sense, because initiallytimedoes not have a string to which you concatenate anything.
```
time = strcpy(time, day_char);
time = strcat(time, "-");
time = strcat(time, hour_char);
```
Better yet, usesprintf:
```
sprintf(time, "%s-%s", day_char, hour_char);
```
|
how can i prevent or bypass the garbage valus malloc puts in my variable?
attached the code and the output!
thanks!
```
#include <stdio.h>
#include "stdlib.h"
#include <string.h>
int main() {
char* hour_char = "13";
char* day_char = "0";
char* time = malloc(strlen(hour_char)+strlen(day_char)+2);
time = strcat(time,day_char);
time = strcat(time,"-");
time = strcat(time,hour_char);
printf("%s",time);
free(time);
}
```
this is the output i get:
```
á[┼0-13
```
|
The firststrcatis incorrect, becausemalloc-ed memory is uninitialized. Rather than usingstrcatfor the first write, usestrcpy. It makes sense, because initiallytimedoes not have a string to which you concatenate anything.
```
time = strcpy(time, day_char);
time = strcat(time, "-");
time = strcat(time, hour_char);
```
Better yet, usesprintf:
```
sprintf(time, "%s-%s", day_char, hour_char);
```
|
The newer versions of gcc offer theWimplicit-fallthrough, which is great to have for most switch statements. However, I have one switch statement where I want to allow fall throughs from all case-statements.
Is there a way to do an explicit fall through? I'd prefer to avoid having to compile withWno-implicit-fallthroughfor this file.
EDIT: I'm looking for a way to make the fall through explicit (if it's possible), not to turn off the warning via a compiler switch or pragma.
|
Use__attribute__ ((fallthrough))
```
switch (condition) {
case 1:
printf("1 ");
__attribute__ ((fallthrough));
case 2:
printf("2 ");
__attribute__ ((fallthrough));
case 3:
printf("3\n");
break;
}
```
|
I learned C language and I have some questions.
If the best way to find address of the beginning of a memory area is to use pointers?
For example in a few steps
I have variable inta = 1;I declare pointer to variable a:int *pointer_a;I assign variable a to pointer:pointer_a = a;Now, I want to print address in memory area:printf("Adress variable a= %p", &pointer_a);
Am I doing it right?
|
pointer_ashould hold memory address of variablea, that's what pointers do. as far as pointers are concern&is theaddress of operator.
```
pointer_a = &a;
```
and then you can.printf("Address variable a = %p", pointer_a);
you can still directlyprintf("Address variable a = %p", &a);
|
Is there any way to store mobile numbers with starting '0' and having 8 or 9 in c without getting the error invalid 8 or 9 in octal constant?
|
If you're not planning on doing math on a "number", then use a char array, not an int. Just because something looks like an integer doesn't mean your program should treat it as one.
|
Thepause()function blocks until a signal arrives.
Assuming the process got a signal and pause() returned, does the signal handler will be executedbeforethe code that follows thepause()call, or the result is unexpected?
Example:
```
void sigusr1_handler()
{
// .. handler code
}
void main()
{
// .. bind handler to SIGUSR1
pause(); // wait for SIGUSR1
// some more code
}
```
Does "some more code" will always be executedaftersigusr1_handler()has finished, or there is a race condition? If so, what is the solution?I cannot think of anything besides busy-waiting, but then the pause won't be needed at all..
|
Citing fromthe man page for pause(2):
pause()returns only when a signal was caught and the signal-catching function returned. In this case,pause()returns -1, anderrnois set toEINTR.
You can be sure that your signal handler runs beforesome more code.
|
I've got this code to populate matrix with 0/1 values and RHO density. I need the same for values from 0 to 2. I mean, the percentage of zeros should be the same, but other values in range 1-2.
```
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
grid[cur][i][j] = (((float)rand())/RAND_MAX) < rho;
}
}
```
The only thing I've been able to do is something inelegant like this. This leaves zero/non zero percentage inalterate and random modifies the 1 cells:
```
...
if(grid[cur][i][j] > 0) {
grid[cur][i][j] += rand()%2;
}
```
|
I think this code will create 0 with RHO density and other values in range 1-2.
```
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
grid[cur][i][j] = (((float)rand())/RAND_MAX) < rho ? 0 : rand() % 2 + 1;
}
}
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.