question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I was trying to understand in which segment constant data is stored.
for example
```
const int x = 100
```
1) Where x is stored? In code segment or data segment?
2) is there any 'read only' data segment exists in initialized data segment?
|
The data will be stored in any segment, or multiple segments, or no segment at all, depending on the specifics of the compiler, compiler flags, linker, linker flags, and surrounding code.
On Linux/ELF, if it is stored somewhere, it willusuallyget stored in the.rodatasection which is inside a segment withr-xpermission... |
I am writing a WarGames server (emulating the W.O.P.R. from the movie) that listens for connections over telnet, in C.
When the main character dials into the W.O.P.R. for the first time, it prints two empty lines, filled with spaces before the login prompt. I want to emulate this in my server.
My question is this: H... |
The telnet protocol does have some stuff for that, but as with anything in C it'll take some reading for the full details:http://www.ietf.org/rfc/rfc1073.txt
IAC SB NAWS <16-bit value> <16-bit value> IAC SE
Sent by the Telnet client to inform the Telnet server of the window width and height.
|
This question already has answers here:Array index out of bound behavior(10 answers)Closed9 years ago.
I am curious about below code in C
```
int main(){
int arr[10];
*(arr+120) = 5;
int *px = arr;
int i = 0;
for(i = 0; *px != 5; px++){
i++;
}
print... |
C does not check array bounds, and the code accessing out-of-array elements is undefined behaviour, which means that anything may happen - including the result you got.
|
I am trying to use the classical pattern:
```
for (void *cur = vec_first(v); cur != NULL; cur = vec_next(v, cur))
```
Using the following function for next:
```
void *vec_next(const Vector *v, const void *prev)
{
void *next = (char*) prev + v->elemsz;
return next;
}
```
When cur is NULL, I imagine the ve... |
When you reach the end of the array and add v->elemsz, the result isn't NULL. It's rubbish.
|
I have used Doxygen for years with C++ code. I'd like to use it with some C code that I'm working on, but the output is less than optimal. The "Classes" tab in the top bar shows only thestructdefinitions, not the functions in the file. I have to click on the "Files" tab and then the name of the header file to view the... |
You can set
```
OPTIMIZE_OUTPUT_FOR_C = YES
```
in the config file, to get output that is more C oriented.
|
I used cdecl and get its definition as "declare papi as array 10 of pointer to pointer to int"
So I write my code in this way
```
int i = 10;
int *api[10];
api[0] = &i;
int *(*papi[10]);
papi = &api;
```
And I got an error says "array type 'int([10])' is not assignable"
What is the correct way to use the papi?
|
Array names are non-modifiable l-values. You can't use them as left operand of=operator.papiis an array name. Change
```
int *(*papi[10]);
```
to
```
int *(*papi)[10]; // papi is a pointer to an array of 10 pointers to int
```
|
While reading most of the open-source code, I frequently see thatenumvalues end with a_BUTTspecifier? It may sound naive, but is there any significance for such coding style?
Example 1:
```
typedef enum __nvp1114a_samplerate {
NVP1114A_8000,
NVP1114A_16000,
NVP1114A_32000,
NVP1114A_44... |
The value of the last_BUTTconstant is the number of constants (excluding the_BUTTone) in the enumerated type.
This last constant is not required and its presence as well as its naming is just a personal choice of the programmer.
|
```
int i=1,j;
j= ++i + ++i;
printf("%d",j);
```
The output of this program is6in C.But when I use the same logic for C#,
the output is5.
I want to know the reason why the same logic behaves differently in two different languages
|
The rule in C# is "evaluate each subexpression strictly left to right". Therefore
```
j= ++i + ++i ;
```
iswell defined in C#but the same expression invokesundefined behaviorin C because you can't modify a variable more than once between twosequence points.
C-FAQ:
The Standard states thatBetween the previous and n... |
In some Linux-based operating systems (like Ubuntu) you can download from the internet within Terminal using theapt-getcommand. When you download something, it shows how much of the package has been downloaded as a percentage. This percentage changes as the package downloads. How can I make a C program behave in a sim... |
Well, add a fflush(stdout) after every printf to force the flshing
|
```
struct settings {
size_t maxbytes;
int maxconns;
int port;
int udpport;
int chunk_size;
};
```
Just as shown above, define a structsettings, and access the struct member likesettings.chunk_size, I come across this usage in the memcached source code,is that OK? If true, what is the function?
|
You cannot access thestructure memberwithstructure name. You have to declare a structure object for accessing.
```
struct settings {
size_t maxbytes;
int maxconns;
int port;
int udpport;
int chunk_size;
};
```
struct settings p1; //Declaring a structure variable
Now you can access the members us... |
I have this function (written in C++ here):
```
GameSession *theSession = NULL;
...
...
startSesion(&theSession)
```
I have managed to get this running properly using the LuaJIT FFI here:
```
local session = ffi.new("GameSession*[1]", {})
myDLL.startSession(session))
```
However, I now need this function in LuaJIT... |
As perFFI Tutorial, you dereference pointers like this:
```
theSession[0];
```
|
My professor gave us the code to get input from a text file. The issue is it will not compile properly for me. I'm not sure where he (or I) went wrong. I have not modified his code in any way and my txt file is in the same directory as the code.
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;... |
chshould be anintanyway
The functionfgetc()will always return anint, to handle all the char values andEOFwhich is negative.
Here reading your file will prematurely end when finding character0xFF.
For the compiling issue, changegetch()intogetchar()
|
I like pointer notation in C more than I like array notation, but just can't figure it out for some cases. I have the following code, and the body ofmain
```
/*converts arguemnt to number using atoi()*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int i, times;
if(argc < 2 || (ti... |
argv[i]is equivalent to*(argv + i)
I really can't imagine why you would prefer the latter over the former.
|
This question already has answers here:Math-like chaining of the comparison operator - as in, "if ( (5<j<=1) )" [duplicate](4 answers)Closed9 years ago.
```
#include <stdio.h>
int main() {
int a = 10, b = 20, c = 30;
if (c > b > a)
printf("TRUE");
else
printf("FALSE");
return 0;
}
```
What happens at if(c>b... |
Operator>is left associative thereforec > b > awill be parenthesize as((c > b) > a). Since30is greater than20,c > b = 1. So,
```
(c > b) > a => (1 > a) => 1 > 10 => false
```
|
It is clear that initializing a char array like
```
char* string = "foobar";
```
will make it immutable. On the other hand, initializing a char array like
```
char string[] = "foobar";
```
will be make it mutable.
What is the best way to make a mutable initialization of pointer to a char array?
```
// member ch... |
Assuming you have C99 features at your disposal, compound literals do the trick:
```
char *arr[] = { (char[]){"foo"}, (char[]){"bar"} };
```
|
Is there anyway? I cant seem to find any function that does this. I tried googling this but could not find anything.
|
I do not believe it is possible. The terminal is not for such things. It is meant for displaying text in sometimes varying colors. If you want to change the font size, you would need to open a window and draw to it (That might not actually be the correct term. Graphics aren't my forte). If this is what you want to do... |
I need to extract the text between 2 string patterns in c.
Example:
```
aaaaaa<BBBB>TEXT TO EXTRACT</BBBB>aaaaaaaaa
PATTERN1=<BBBB>
PATTERN2=</BBBB>
```
Thanks.
|
Here is an alive example of how to do this
```
#include <stdio.h>
#include <string.h>
int main(void)
{
const char *s = "aaaaaa<BBBB>TEXT TO EXTRACT</BBBB>aaaaaaaaa";
const char *PATTERN1 = "<BBBB>";
const char *PATTERN2 = "</BBBB>";
char *target = NULL;
char *start, *end;
if ( start = strs... |
I am curious to know the use of parentheses for bothfilpandxpointers in the following assignment operation:
```
#define init_sync_kiocb(x, filp) \
do { \
struct task_struct *tsk = current; \
(x)->ki_flags = 0; \
(x)->ki_users = 1; \
(x)->ki_key = KIOCB_SYNC_KEY; \
(x)->ki_filp = (filp); \ // This line here
...... |
These are used in a macro definition which is handled by the preprocessor as text substitution. The fact that it is text substitution can result in weird expressions. Consider:
```
p = &a_struct_array[10];
init_sync_kiocb(p + 20, filp)
```
without the parens, it turns into:
```
p + 20->ki_filp = (filp);
```
with t... |
I have been trying to use ioctl to get the state of my wifi connection, but have run into a problem: whenever i do#include <linux/wireless.h>, gcc generates lots of errors, e.g.
```
/usr/include/linux/wireless.h:869:18: error: field ‘src_addr’ has incomplete type
struct sockaddr src_addr;
^
/usr/inclu... |
You need the include of sockaddr.
You have to include:
```
#include <netinet/in.h>
#include <sys/socket.h>
```
|
I am writing a PHP extension in C that includes PHP classes defined in C. I would like to set a static property on one of the classes. In particular, I would like to do in C the equivalent of
```
class Example{
public static $member;
}
Example::member = new Example();
```
I can't use theREGISTER_*_CONSTANTmacros ... |
You cannot actually register a static property, instead you just have to update it, and have PHP do the registering for you.
http://php.undmedlibrary.org/manual/en/zend-api.zend-update-static-property.php
```
// int zend_update_static_property ( zend_class_entry* $scope, char* $name, int $name_length, zval* ... |
I've isolated a memory leak to these lines:
```
char* word_ptr;
while(read_word(fp, word)) {
word_ptr = strdup(to_lower_case(word));
// other stuff happens, loop closes properly, etc.
```
Since I don't malloc word_ptr, I don't need to free it. If you need the lowercase function, it is here:
```
char* to_low... |
Since I don't malloc word_ptr ...
Butstrdup()allocates memory withmalloc(), so it is all the same.
Fromman 3 strdup:
Memory for the new string is obtained withmalloc(3), and can be freed withfree(3).
|
I'm trying to write a macro in C that gets a byte (char) and an index, then it reads theindexth bit from that byte.
This is what I got:
```
#define READBIT(byte, index) (byte) & (1 << (index))
```
And this is how I check it:
```
for (i = 7; i >= 0; i--)
{
printf("%d", READBIT('a', i));
}
```
It prints064320000... |
```
#define READBIT(byte, index) (((unsigned)(byte) >> (index)) & 1)
```
Noting that>>and<<are better defined for unsigned values.
|
I would like to insert in my program a spin button to change a time interval. In particular, it should visualize a time in the formathh:mm:ssand the spin button should increase/decrease of one second the time inverval.
How can I achieve this?
|
Use the "output" signal of GtkSpinButton [1]. This allows a hook for setting the underlying GtkEntry text when the value changes. The docs already provide a good example so I will leave that out of my answer. Similarly if you accept user input in the same format, the "input" signal can be used to parse the custom form... |
For example:
```
if(mvwinch(win,y,x=(oldx-1))=='X')
```
Is the value of the variable 'x' now changed?
|
Before comparison, both expressions will be evaluated and any side effect could take place during the evaluation. So, yesxwould be modified.
|
I have been trying to use ioctl to get the state of my wifi connection, but have run into a problem: whenever i do#include <linux/wireless.h>, gcc generates lots of errors, e.g.
```
/usr/include/linux/wireless.h:869:18: error: field ‘src_addr’ has incomplete type
struct sockaddr src_addr;
^
/usr/inclu... |
You need the include of sockaddr.
You have to include:
```
#include <netinet/in.h>
#include <sys/socket.h>
```
|
I am writing a PHP extension in C that includes PHP classes defined in C. I would like to set a static property on one of the classes. In particular, I would like to do in C the equivalent of
```
class Example{
public static $member;
}
Example::member = new Example();
```
I can't use theREGISTER_*_CONSTANTmacros ... |
You cannot actually register a static property, instead you just have to update it, and have PHP do the registering for you.
http://php.undmedlibrary.org/manual/en/zend-api.zend-update-static-property.php
```
// int zend_update_static_property ( zend_class_entry* $scope, char* $name, int $name_length, zval* ... |
I've isolated a memory leak to these lines:
```
char* word_ptr;
while(read_word(fp, word)) {
word_ptr = strdup(to_lower_case(word));
// other stuff happens, loop closes properly, etc.
```
Since I don't malloc word_ptr, I don't need to free it. If you need the lowercase function, it is here:
```
char* to_low... |
Since I don't malloc word_ptr ...
Butstrdup()allocates memory withmalloc(), so it is all the same.
Fromman 3 strdup:
Memory for the new string is obtained withmalloc(3), and can be freed withfree(3).
|
I'm trying to write a macro in C that gets a byte (char) and an index, then it reads theindexth bit from that byte.
This is what I got:
```
#define READBIT(byte, index) (byte) & (1 << (index))
```
And this is how I check it:
```
for (i = 7; i >= 0; i--)
{
printf("%d", READBIT('a', i));
}
```
It prints064320000... |
```
#define READBIT(byte, index) (((unsigned)(byte) >> (index)) & 1)
```
Noting that>>and<<are better defined for unsigned values.
|
I would like to insert in my program a spin button to change a time interval. In particular, it should visualize a time in the formathh:mm:ssand the spin button should increase/decrease of one second the time inverval.
How can I achieve this?
|
Use the "output" signal of GtkSpinButton [1]. This allows a hook for setting the underlying GtkEntry text when the value changes. The docs already provide a good example so I will leave that out of my answer. Similarly if you accept user input in the same format, the "input" signal can be used to parse the custom form... |
For example:
```
if(mvwinch(win,y,x=(oldx-1))=='X')
```
Is the value of the variable 'x' now changed?
|
Before comparison, both expressions will be evaluated and any side effect could take place during the evaluation. So, yesxwould be modified.
|
I have the follow line of C code:
```
sprintf (ptr, "<th width=\"25%\">Head One</th>\n");
```
I have tried combinations of replacements:
Replacing:\"with""Replacing%with%%
But on compilation, using a Makefile, all produce the same error:
```
warning: unknown conversion type character `"' in format
```
Any sugges... |
Usestrcpy()since you don't want formatting (orstrlcpy()/strcpy_s()for safety).Doubling the percent should work, and if you getthe sameerror then that of course points at something being wrong in your build environment.
|
Here is the code I'm running:
```
#include <iostream>
using namespace std;
int main()
{
int x = 5;
int *p;
p = &x;
*p++;
cout<<x<<endl;
return 0;
}
```
The output should be 6, becausepis pointing at the address ofx. However, I get 5.
But more interestingly, I couldn't understand why the out... |
You are wrong. *p++ reads the value that p points to, then increases the pointer p. You probably wanted (*p)++.
*p = *p + 1 works because it is correct.
|
I have inherited the following code and would like to know more about the indexing used.
```
...
char cpChMap[256];
memset(cpChMap, 0xff, 256);
for (i = 0; i < 10; i++)
cpChMap['0' + i] = 0;
...
```
I have never seen a char used to index and array before [cpChMap[<character expression>]], can someone explain how... |
charis an integral type. They can be used in arithmetic expressions:
```
std::cout << '0' + 7 << std::endl;
```
The fact that'0'through'9'are contiguous implies that'0' + 7has the same value of'7', that's why in the loop:
```
for (i = 0; i < 10; i++)
cpChMap['0' + i] = 0;
```
cpChMapuses index'0'(the same as48... |
Learning AVR C programming i end up getting a warning from
```
int ISR(USART0_RX_vect) {
// blah blah blah...
return 0;
}
//Warning 1 type of 'USART0_RX_vect' defaults to 'int' [enabled by default]
```
Why is this warning appearing and what actions are required to remove it?
|
From what I can tell your syntax is just wrong.ISRis a macro that simplifies the definition of an interrupt handler routine.ISRresolves to an__attribute__decorated function which signature already specifies the return typevoid.
USART0_RX_vectwill be resolved to something like__vector_18(ATMEGA128).
Something like th... |
Can anyone give me a hint how to work with Android InputStream in native code.
More specific example:
Java code
```
public class SomeParser {
public native ArrayList<String> parse(InputStream stream);
}
```
I need to read InputStream in native and return matching patterns to Android Java code.streamis BufferedI... |
You needd to pass a reference to theStreamthrough JNI to your native code, and then use JNI calls to act upon it. You will probably get java byte-arrays. These you can copy to native arrays using JNI. It is all standard JNI.
|
If I typeint xis it usingsizeof(int)bytes of memory now? Is it not until x has a value?
What ifx = b + 6...is x given a spot in memory before b is?
|
Yes, as soon as you declare a variable like:
```
int x;
```
memory is, generally, allocated on the stack. That being said, the compiler is very smart. If it notices you never use that variable, it mayoptimize it away.
|
I want to design an EAP-TLS client. As the protocol works on the ethernet layer, I am using raw sockets in C and designing the handshake step by step. I wanted to get the TLS data into the packet i designed using OpenSSL. The examples I found online used SSL_Connect() with a socket descriptor and sent the data. I howe... |
If you want to have everything in your own buffer and not send directly to the socket you have to use not a file descriptor, but a memory BIO as the lower layer for SSL and then you can use the usual SSL_ functions on top of it. You might have a look atDirectly Read/Write Handshake data with Memory BIO. A working impl... |
Is it possible to use a switch statement without a jump table? GCC creates stupid (and in my case unusable) jump tables which I want to avoid.
| ERROR: type should be string, got "\nhttps://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html\n\n-fno-jump-tables\n\nDo not use jump tables for switch statements even where it would be more efficient than other code generation strategies. This option is of use in conjunction with -fpic or -fPIC for building code that forms part of a dynamic linker and cannot reference the address of a jump table. On some targets, jump tables do not require a GOT and this option is not needed.\n" |
Are the following twostaticvariable declarations equivalent?
1.
```
static int var1;
static int var2;
static int var3;
```
2.
```
static int var1, var2, var3;
```
More specifically, in case 2, will all variables bestatic, or justvar1?
|
They're equivalent.
In case 2, all the variables will be static.
The storage class specifierstaticapplies to all the declared variables in the declaration.
|
This question already has answers here:#define IDENTIFIER without a token(4 answers)Closed9 years ago.
First, it declares the macroLOG_DBG(x)just like this:
```
#define LOG_DBG(x)
```
And then, use it like this:
```
LOG_DBG((LOG_MISC, 80, __FUNCTION__": select reports %d", res));
```
And I can't understand what t... |
It does exactly nothing. It gets preprocessed to an empty string. This may be a somewhat convenient way of disabling/enabling debug log messages. The code was probably written like this at some point:
```
#define LOG_DBG(x) some_logging_function(x)
```
But then someone wanted to simply get rid of all the log message... |
Recently I was asked a very tricky question in an interview.
Given an array like (just for example)Now write an optimized algorithm (without using in build feature except the basic one like for loop etc.) so that the output does not contain duplicate values.
Please Note:Of course we can do it having 2 for loops, but... |
In c# just use the System.LinqDistinctmethod.
Sample
```
var stringArray = { "0", "1", "5", "65", "r" };
var uniqueStringArray = stringArray.Distinct().ToArray();
```
More Information
Enumerable.Distinct
|
```
int ar[3][3]={{1,2,3},{4,5,6},{7,8,9}};
statment1: int k=(int *)((int *)(ar+1)+2);
statment2: int l=*(*(ar+1)+2);
statement3 int *p = (int *)a +1;
```
Statement1 does not compile.
Statement2 and Statement3 compiles.
Now, I cannot make out what difference does it make if I put(int *)instead of*, given that th... |
You are confused about dereference operator*and cast operation(int *), and your very 1st line should have ring a bell:
```
int k = (int *)bar;
```
You try to affect an address (pointer toint) in anintvariable.
The 2nd is ok because you are using*twice to get a value in your 2-dimension array.
The 3rd is also ok bec... |
Literally, does(char *) 0mean a pointer to some location that contains a zero? Does the system create such an address with value 0 for each such declaration?
|
No, it's a cast of0to typechar *. That is, anull pointer. A0in any pointer context refers to thenull pointer constant.
Whatexactly it points to doesn't matter - dereferencing it would cause undefined behaviour.
For more, check out theC FAQ Part 5: Null Pointers.
|
This question already has answers here:#define IDENTIFIER without a token(4 answers)Closed9 years ago.
First, it declares the macroLOG_DBG(x)just like this:
```
#define LOG_DBG(x)
```
And then, use it like this:
```
LOG_DBG((LOG_MISC, 80, __FUNCTION__": select reports %d", res));
```
And I can't understand what t... |
It does exactly nothing. It gets preprocessed to an empty string. This may be a somewhat convenient way of disabling/enabling debug log messages. The code was probably written like this at some point:
```
#define LOG_DBG(x) some_logging_function(x)
```
But then someone wanted to simply get rid of all the log message... |
Recently I was asked a very tricky question in an interview.
Given an array like (just for example)Now write an optimized algorithm (without using in build feature except the basic one like for loop etc.) so that the output does not contain duplicate values.
Please Note:Of course we can do it having 2 for loops, but... |
In c# just use the System.LinqDistinctmethod.
Sample
```
var stringArray = { "0", "1", "5", "65", "r" };
var uniqueStringArray = stringArray.Distinct().ToArray();
```
More Information
Enumerable.Distinct
|
```
int ar[3][3]={{1,2,3},{4,5,6},{7,8,9}};
statment1: int k=(int *)((int *)(ar+1)+2);
statment2: int l=*(*(ar+1)+2);
statement3 int *p = (int *)a +1;
```
Statement1 does not compile.
Statement2 and Statement3 compiles.
Now, I cannot make out what difference does it make if I put(int *)instead of*, given that th... |
You are confused about dereference operator*and cast operation(int *), and your very 1st line should have ring a bell:
```
int k = (int *)bar;
```
You try to affect an address (pointer toint) in anintvariable.
The 2nd is ok because you are using*twice to get a value in your 2-dimension array.
The 3rd is also ok bec... |
Literally, does(char *) 0mean a pointer to some location that contains a zero? Does the system create such an address with value 0 for each such declaration?
|
No, it's a cast of0to typechar *. That is, anull pointer. A0in any pointer context refers to thenull pointer constant.
Whatexactly it points to doesn't matter - dereferencing it would cause undefined behaviour.
For more, check out theC FAQ Part 5: Null Pointers.
|
I have the following C code example:
```
int f(const int farg[const 5])
{
}
```
What does the additional const for the array size do? And what is the difference when I omit the const there?
|
```
int d(const int darg[5])
```
Meansdargis a pointer toconstint.
```
int e(int earg[const 5])
```
Meanseargis aconstpointer toint. This is a c99 feature.T A[qualifier-list e]is equivalent asT * qualifier-list Ain the parameter declaration.
And of course (from above):
```
int f(const int farg[const 5])
```
Mea... |
What is this code doing exactly:
```
char* pointer=0;
*pointer=0;
```
Every time I run this code, the programme crashes!
|
First line: You create apointervariable to a char, then you initialize it to address zero (NULL pointer).
Second line: you try to write a zero to the address wherepointeris pointing to.
Address zero is outside of your process' writable virtual memory area, so you get a segmentation fault.
|
First of all I like to mention that I am using eclipse.
This is the example file structure
source/file.h
source/additionalsource/file.h
thing to note is that both header files have the same name.
so including source/ and source/additionsource to include paths and writing #include "file.h" Does not work since ther... |
Try this:
```
#include "./additionalsource/file.h"
```
|
I have the following C code example:
```
int f(const int farg[const 5])
{
}
```
What does the additional const for the array size do? And what is the difference when I omit the const there?
|
```
int d(const int darg[5])
```
Meansdargis a pointer toconstint.
```
int e(int earg[const 5])
```
Meanseargis aconstpointer toint. This is a c99 feature.T A[qualifier-list e]is equivalent asT * qualifier-list Ain the parameter declaration.
And of course (from above):
```
int f(const int farg[const 5])
```
Mea... |
What is this code doing exactly:
```
char* pointer=0;
*pointer=0;
```
Every time I run this code, the programme crashes!
|
First line: You create apointervariable to a char, then you initialize it to address zero (NULL pointer).
Second line: you try to write a zero to the address wherepointeris pointing to.
Address zero is outside of your process' writable virtual memory area, so you get a segmentation fault.
|
First of all I like to mention that I am using eclipse.
This is the example file structure
source/file.h
source/additionalsource/file.h
thing to note is that both header files have the same name.
so including source/ and source/additionsource to include paths and writing #include "file.h" Does not work since ther... |
Try this:
```
#include "./additionalsource/file.h"
```
|
I have a Raspberry Pi with a small touch display (320x240) which I want to use as a simple user interface for my robot. For this purpose, I am looking for a basic user interface library for C/C++ which allows me to have a very basic mouse supported UI without using any window manager. Unfortunately, a TUI is not a via... |
I recomendSFMLorAllegro? It's lightweight graphic lib and should fullfill all your requirements.
|
Please find below code snippet. Is there any chance whereinstrncatandmemcpywill have different values inpDBVal. If so, Please explain.
```
memcpy(pDBVal, pHash, 20);
strncat(pDBVal, cBinSalt, 16);
memcpy(pDBVal+20,cBinSalt,16);
```
Ideally output in pDBVal will be same. Also please explain the difference in execu... |
strncatis supposed to be used for string concatenation, so in
```
strncat(pDBVal, cBinSalt, 16);
```
If the length ofcBinSaltis less than16, only the content up to'\0'is copied.
|
The C99 standard of the C programming language defines the_Booldata type as a macro for another data type (as the language isn't able to deal with a type safe boolean).
Is the_Boola macro forunsigned char,unsigned intor some other data type?
|
_Boolis a separate integer type that according to the C Standard._Boolis akeywordof the C language.
2 An object declared as type _Bool is large enough to store the values
0 and 1.
_Boolis unsigned integer type.
The type _Bool and the unsigned integer types that correspond to the
standard signed integer types are th... |
In Java, why doesn't the compiler simply assume that an uninitialised variable should have 0 as its value, like C does? Is this just BetterPractice in general, or is there another reason that is particular to Java?
|
Because the code that uses a variable that has not been initialized, leading to unpredictable or unintended results.I guess java designers must have faced lot of problems while programming with C like stuck in loop, So probably when they were developing java they decided to get rid of this problem. And that is why we ... |
I don't understand what kind of property themysterymember is below:
```
typedef struct _myobject
{
long number;
void *mystery;
} t_myobject;
```
What kind of member is thisvoidmember? How much memory does that take up? Where can I get more information about what that accomplishes (for instanc... |
Avoid*variable is a "generic" pointer to an address in memory.
The fieldmysteryitself consumessizeof(void*)bytes in memory, which is typically either 4 or 8, depending on your system (on the size of your virtual memory address space, to be more accurate). However, it may point to some other object which consumes a di... |
Please find the below code snippet.
```
unsigned char bInput[20];
unsigned char cInput[20];
```
From a function, I get a binary data inbInputand I determined its length usingstrlen(bInput).
I convertedbInputwhich is in binary to ASCII and stored incInputand printed its length. But both are different.
I am new to pr... |
Functionstrlenreturns the index of the first character in memory with a value of 0 (AKA'\0'), starting from the memory address indicated by the input argument passed to this function.
If you pass a memory address of "something else" other than a zero-terminated string of characters (which has been properly allocated ... |
I need to enter a very long string for which I don't need to reserve any memory (no need to read the string later, just once character by character). How can I process the string without receiving the complete string?
This is my code snippet:
```
for(length = n; length > 0; length--) {
input = getchar();
if ... |
If I get it correctly then you may try like this:
```
while (1)
{
char c = (char)getchar();
if(c=='\n')
break;
// do your logic here
}
```
|
Question 1:
```
int main()
{
char *p="abcd";
printf("%c",*(p++));
return 0;
} // Here it will print a
```
Question 2:
```
int main()
{
char *p="abcd";
printf("%c",++*(p++));//why it is showing error over here
return 0;
} // Here it shows runtime error.
```
Can someone please explain to me why the stat... |
```
char *p="abcd";
```
"abcd"is a string literal and string literals are unmodifiable in C. Attempting to modify a string literal invokes undefined behavior.
Use a modifiable array initialized by a string literal to fix your issue:
```
char p[] ="abcd";
```
|
How can I create a mutex in linux that will work with different processes and will have string name?
I want something similar toCreateMutexin Windows OS.
|
Use a semaphore - seehttp://man7.org/linux/man-pages/man7/sem_overview.7.html.
This will give you the same as a mutex and you can name them
|
I want get the values in EAX/EBX/ESP/EIP etc. and save them in C variables. For example:
```
int cEax;
asm("mov cEax,%eax"); ...
```
|
You can use this
```
register int eax asm("eax");
register int eax asm("ebx");
register int eax asm("esp");
//...
int cEax = eax;
int cEbx = ebx;
int cEsp = esp;
//...
```
You can also work with those registers in an expression just as any other variables or just use that register's value directly without assigning ... |
I read ithere, but I'm unable to grasp it.
```
//assume a and b are char arrays
scanf("%[^,]s",a); // first scanf()
scanf("%[^,],s",b); // second scanf()
```
I can understand that the firstscanf()will scan the string until','is encountered. But what about the second one?
Thislinksays that the firstscanf()w... |
scanf("%[^,]s",a);will read up to,and thenleave,in input buffer .scanf("%[^,],s",a);will read up to,and after reading,, it willdiscardit.
And both of them will read and discard the trailings.
Try this sample code and see the difference:
```
#include <stdio.h>
int main()
{
char a[10];
char b;
scanf("%[^,]s"... |
I have a array made of strings arrays:
char ***t = NULL;
I am filling it dynamically with stringss, and so I use thereallocfunction like this:
```
int sumchars = 0;
for i, j... :
s = result(i, j);
sumchars += strlen(s);
t = realloc(t, sumchars * sizeof(char));
t[i][j] = s;
```
This gives me a Segmentat... |
No need to usereallocin this case. Try this instead:
```
t = realloc(t, ROW*sizeof(char**));
for(int i = 0; i < ROW; i++)
{
t[i] = NULL;
t[i] = malloc(COL*sizeof(char *));
}
for(...)
{
s = result(i, j);
t[i][j] = s;
}
```
|
Please find the below code snippet.
```
unsigned char bInput[20];
unsigned char cInput[20];
```
From a function, I get a binary data inbInputand I determined its length usingstrlen(bInput).
I convertedbInputwhich is in binary to ASCII and stored incInputand printed its length. But both are different.
I am new to pr... |
Functionstrlenreturns the index of the first character in memory with a value of 0 (AKA'\0'), starting from the memory address indicated by the input argument passed to this function.
If you pass a memory address of "something else" other than a zero-terminated string of characters (which has been properly allocated ... |
I need to enter a very long string for which I don't need to reserve any memory (no need to read the string later, just once character by character). How can I process the string without receiving the complete string?
This is my code snippet:
```
for(length = n; length > 0; length--) {
input = getchar();
if ... |
If I get it correctly then you may try like this:
```
while (1)
{
char c = (char)getchar();
if(c=='\n')
break;
// do your logic here
}
```
|
Question 1:
```
int main()
{
char *p="abcd";
printf("%c",*(p++));
return 0;
} // Here it will print a
```
Question 2:
```
int main()
{
char *p="abcd";
printf("%c",++*(p++));//why it is showing error over here
return 0;
} // Here it shows runtime error.
```
Can someone please explain to me why the stat... |
```
char *p="abcd";
```
"abcd"is a string literal and string literals are unmodifiable in C. Attempting to modify a string literal invokes undefined behavior.
Use a modifiable array initialized by a string literal to fix your issue:
```
char p[] ="abcd";
```
|
How can I create a mutex in linux that will work with different processes and will have string name?
I want something similar toCreateMutexin Windows OS.
|
Use a semaphore - seehttp://man7.org/linux/man-pages/man7/sem_overview.7.html.
This will give you the same as a mutex and you can name them
|
I want get the values in EAX/EBX/ESP/EIP etc. and save them in C variables. For example:
```
int cEax;
asm("mov cEax,%eax"); ...
```
|
You can use this
```
register int eax asm("eax");
register int eax asm("ebx");
register int eax asm("esp");
//...
int cEax = eax;
int cEbx = ebx;
int cEsp = esp;
//...
```
You can also work with those registers in an expression just as any other variables or just use that register's value directly without assigning ... |
I read ithere, but I'm unable to grasp it.
```
//assume a and b are char arrays
scanf("%[^,]s",a); // first scanf()
scanf("%[^,],s",b); // second scanf()
```
I can understand that the firstscanf()will scan the string until','is encountered. But what about the second one?
Thislinksays that the firstscanf()w... |
scanf("%[^,]s",a);will read up to,and thenleave,in input buffer .scanf("%[^,],s",a);will read up to,and after reading,, it willdiscardit.
And both of them will read and discard the trailings.
Try this sample code and see the difference:
```
#include <stdio.h>
int main()
{
char a[10];
char b;
scanf("%[^,]s"... |
I have a array made of strings arrays:
char ***t = NULL;
I am filling it dynamically with stringss, and so I use thereallocfunction like this:
```
int sumchars = 0;
for i, j... :
s = result(i, j);
sumchars += strlen(s);
t = realloc(t, sumchars * sizeof(char));
t[i][j] = s;
```
This gives me a Segmentat... |
No need to usereallocin this case. Try this instead:
```
t = realloc(t, ROW*sizeof(char**));
for(int i = 0; i < ROW; i++)
{
t[i] = NULL;
t[i] = malloc(COL*sizeof(char *));
}
for(...)
{
s = result(i, j);
t[i][j] = s;
}
```
|
How do I test to see if I am linking in C++ or C using macros?
Say I have code that should link as C in a C++ file, I would useextern "C"{//code here}which would make my code in a link as C . How would I set up myname.cfile to work for both C and C++. Something like...
```
#ifdef C++//or other macro
extern "C"{
#endi... |
"What is the proper macro to replace the "C++""
It's#ifdef __cplusplus
```
#ifdef __cplusplus
extern "C"{
#endif
//.....
#ifdef __cplusplus
}
#endif
```
For"...What is the significance of having to do....?"
Read :In C++ source, what is the effect of extern “C”?
|
This question already has answers here:Modifying String Literal [duplicate](4 answers)Closed9 years ago.
Where is the problem? When running, the application crashes...
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void test(char* x) {
(*x)++;
}
int main() {
char* x = "xD";
test(x);
... |
You are Trying to modify a string literal that is stored in a read-only memory adress, because withchar* x = "xD";you declare a pointer to that kind of data. use thischar x [] = "xD";instead, that is NOT a pointer, is an array that you are allowed to modify because it is stored in the stack. or if you want to use a po... |
I started learning C and i am still at simple programs but with a ton of errors :/
The following code once it catches the wrong input (in the else statement) will continue running and it wont stop for the next scan... why is that happening?
```
const float inch_to_cm = 2.54;
int main()
{
bool run = true;
flo... |
If you are entering anything else than a numerical value then it will not read byscanfand live there for infinite time causing infinite loop. You must have to flush the input buffer. Place this after theelsestatement:
```
int c;
while((c = getchar()) != '\n' && c != EOF);
```
|
My code as bellow:
```
const size_t NUM_P = 100;
int main (viod)
{
char *pS[NUM_P] = { NULL}; /* Array of string pointer */
/* Other code */
}
```
My compiler is CODEBLOCK, the error will be clear when NUM_P is changed to digits, such as "12,or 35 ..", I don't know the root cause of the error , or i... |
The root of your problem is thatNUM_Pis a variable, even if it is aconstone.
Replace its declaration by#define NUM_P 100and your code will compile again.
|
I will try to make the question clear. I am developing a loadable kernel module and just wondering whether I can call a static inline function defined in another header file of the Linux kernel source.
I understand that the static keyword makes the function restricted within the scope of the compilation unit(i.e. a C ... |
Whether I can call a static inline function defined in another header file of the Linux kernel source??
Yes. Possible.kmalloc()is an example for it. This function is defined ininclude/linux/slab.has astatic inlinefunction. Suggest to readthispost which explains why static inline is used in header files.
Referencesht... |
I'm trying to convert anintto achar*. I'm on a Mac OS X so I can't useitoa, since it's non-standard, I'm trying to usesprintforsnprintfbut I keep on gettingsegmentation fault: 11.
Here's what I've got:
```
snprintf(msg, sizeof(char *), "%d", 1);
```
So I'm hoping for a suggestion, what can I do?
|
It's likely thatmsg, which is achar *, doesn't point to memory that it can use. So you first have to dynamically allocate memory that will be used to store the string.
```
msg = malloc(12); // 12 is an arbitrary value
snprintf(msg, 12, "%d", 1); // second parametre is max size of string made by function
```
Alternat... |
I'm making a little C program that works out the area and circumference of circles, and I want this equation to be worked out, but each time it says "lvalue required as left operand of assignment" for the top line, and "expected expression before "=" token" for the second line I've tried everything i can think of, but... |
Replace your 2 lines with:
```
circ_area = (CircleRadi * CircleRadi) * 3.1415926538;
circ_circum = (CircleRadi * 2 )* 3.1415926538;
```
I'm supposing thatcirc_areaandcirc_circumare bothfloatsand have been declared previously.
|
If I wanted to cast a float or double to an integer type, and I didnt want it to overflow under any circumstances, how should I go about choosing an integer type?
|
The range forfloatsis almost always larger than thelong longorint64(but it can depend on the implementation).
For example, in .Net the range offloatis3.4E +/- 38, but the range forlong longandint64is –9,223,372,036,854,775,808to9,223,372,036,854,775,807. You just can't be sure that you will not overflow. Other implem... |
Whenever I open a .csv file in Excel or Sakura Editor I get an fopen error when running my C program whereas when I open the file in Notepad or Notepad++ I don't get any errors and the file can be used by the program without issues.
What is the difference between the usage of the .csv file amongst these applications ... |
When Excel, and presumably Sakura, open the file, they keep lock it with a share mode that denies other programs write access to the file. On the other hand, Notepad and Notepad++ open the file without locking it, and just read the contents.
If your program is just attempting to read the file, it will be able to succ... |
I have a code which is written in the C programming language. In this code I have more than 200 lines with this commandfprintf(stdout,"--- This is just fo foo! ---\n");. I want to add something likehello fooat the beginning of the output. In this case the result will be like this :
hello foo--- This is just fo foo! -... |
Take this opportunity to do a global search-and-replace on your whole codebase, and change each line to:
```
fo_foo();
```
and add in a common header:
```
inline void fo_foo() { fprintf(stdout, "hello foo--- etc."); }
```
Next time you need to change this string you will only have to do it in one place.
|
I have 3-5 (large-ish) programs that I need merge so that they run sequentially. Speed is important, since this is for (near) real-time applications. (If there is a better way, let me know).
Would it make more sense to write a Bash script to call these other programs or to write a C program that will most likely usef... |
This is the perfect use case for bash. The overhead will be less than a millisecond, and maintenance cost is way lower than for a C program.
|
(1)WHen I am using a FILE pointer in C and forgot to close it. My computer told me that it was a memory leak in the program. I feel does it mean that we dynamically allocate heap space for the file pointer?
|
I do believe the pointer returned by the fopen function is initialized with malloc, so without properly freeing it (using fclose) there will be a memory leak when the program exitsThere should be no need to call fclose if you never used fopen. I can't think of a reason you'd need a FILE pointer if you weren't going to... |
How can I count the number of digits in a number up to 1000 digits in C or C++
```
#include <stdio.h>
int main()
{
int num,counter=0;
scanf("%d",&num);
while(num!=0){
num/=10;
counter++;
}
printf("%d\n",counter);
}
```
This code works just for numbers up to 10 digits — I don't... |
Since most computers can't hold an integer that is 1000 digits, you will either have to operate on the input as a string or use aBig Numberlibrary. Let's try the former.
When treating the input as a string, each digit is a character in the range of'0'to'9', inclusive.
So, this boils down to counting characters:
``... |
I understand what a basic C function declaration means:
return_type function_name(args) { ... }
However, when I was working on a project that I did not write I found a strange declaration that is used repeatedly. I do not understand what it means.
Here's an example:
```
int C74_EXPORT main(void)
{
...
}
```
... |
That's not standard, so it's hard to answer in general.
It's probably a preprocessor macro, which gets replaced by something. That "something" can be compiler-dependent, it usually is.
You should read the preprocessed code to figure this out, or check the Makefile or other build artefacts for a definition of `C74_EX... |
I'm having a problem with getting bunch of files from the very start of my program ("args argv"),
when i run the program: one file is from the ProjectDir and the other one is from sub folder in my projectdir
here is a printscreen of my project properties:
help! please!
|
You don't have to separate params with a,, they're separated with a space characterassuming thatfile.txtis from a sub-directory: you pass a path that points to the directory rightabovethe$(ProjectDir), notbelowthe$(ProjectDir)
Assuming you have this directory structure
```
ProjectDir
|
+- johai.txt
|
+- subd... |
I want a convenient API in c to get the list of sub-volumes in the given btrfs partition as listed out when we run the command below.
btrfs subvolume list btrfs/subvol/path
|
If you can't find a convenient API,popenis what you want:
```
#include <stdio.h>
FILE *popen(const char *command, const char *mode);
int pclose(FILE *stream);
int main(void)
{
FILE *cmd = popen("btrfs subvolume list btrfs/subvol/path", "r");
char result[128];
while (fgets(result, sizeof(result), cmd) !... |
```
printf("Enter the name of file you wish to see\n");
gets(file_name);
fp = fopen(file_name,"rb");
while( ( ch = fgetc(fp) ) != EOF && loop)
{
printf("value of ch is %x\n",ch);
loop--;
}
```
I have a binary file and I read it with "rb" permission.and printing its value in hexadecimal but if ... |
The data itself is not "hexadecimal", it's just a single character (byte, typically) of bits from the file.
You can choose to print it in hexadecimal, or any other format. You can do that regardless if you have the value in an array or not.
|
If I wanted to cast a float or double to an integer type, and I didnt want it to overflow under any circumstances, how should I go about choosing an integer type?
|
The range forfloatsis almost always larger than thelong longorint64(but it can depend on the implementation).
For example, in .Net the range offloatis3.4E +/- 38, but the range forlong longandint64is –9,223,372,036,854,775,808to9,223,372,036,854,775,807. You just can't be sure that you will not overflow. Other implem... |
Whenever I open a .csv file in Excel or Sakura Editor I get an fopen error when running my C program whereas when I open the file in Notepad or Notepad++ I don't get any errors and the file can be used by the program without issues.
What is the difference between the usage of the .csv file amongst these applications ... |
When Excel, and presumably Sakura, open the file, they keep lock it with a share mode that denies other programs write access to the file. On the other hand, Notepad and Notepad++ open the file without locking it, and just read the contents.
If your program is just attempting to read the file, it will be able to succ... |
I am not able to run any C/C++ programs in code::blocks. Could anyone please suggest why this is happening? Currently I have the gnu c and g++ compilers installed on the system.
The error message on building and running this simple c code:
```
#include<stdio.h>
int main(){
printf("55");
return 0;
}
```
is:
... |
You have two options:
Installxterm
or
In CodeBlocks, go toSettings->Environment, go toTerminal to launch console programs, and select an appropriate terminal.
What's currently happening is that CodeBlocks is attempting to run your program withxterm, which isn't installed on your machine.
|
If i use the following codechar * foo = "words". Should i callfree()before i do :foo = "two words";. How does this assignemnt work?
Is the memory containing the string "word" freed , then enough memory to hold the string "two words" then allocated and then foo set to point to the new string. I just want to make sur... |
No, you should only callfreefor an object that you have allocated throughmalloc,callocorrealloc.
"words"is an object with static storage duration and you cannot free the object.
|
My C++ multi threaded application hangs in pthread_spin_lock in valgrind versions 3.8.0 and latest. But it is not happening in 3.6.0, 3.6.1 and 3.7.0. Anyone knows any workaround for this?
|
This is cause the internal problems of thread managing in valgrind. I had same problem and it was fixed in 3.10 version of valgrind.
|
I'm looking at a piece of code that is sending commands from one piece of hardware to another. A snippet is below.
```
unsigned char data[3];
msg_header *mHead; //pointer of struct msg_header
mHead = (msg_header *) &data;
mHead->startByte = START_BYTE;
mHead->ID = GET_TELEM; //0x30
mHead->length = 0;
```
The stru... |
It's casting the address ofdatato amsg_header*type - pointer tomsg_header.
There's no reference to speak of.&can be used to get the address of a variable.
|
In my programm I may close a file that is already close. What happen when I do afcloseon a file already close ?
And if you can't do so, how to know if a file is closed or open ?
|
Callingfclosetwice with the same stream is undefined behaviour - most likely crash. There is no way to check ifFILE*has been closed already, so the safe solution is to set pointer to NULL as soon as it is closed:
```
fclose(fh);
fh = NULL;
```
Sources: "The value of a pointer to a FILE object is indeterminate after ... |
```
#include <cstdio>
using namespace std;
int main()
{
int i,a;
printf("%d",printf("PRINT %d\t",scanf("%d %d",&i,&a)));
return 0;
}
```
This code is giving output
```
PRINT 2 8
```
I want to know how it is giving the same output for any number inputted. I'm a new user and sorry if I'm ... |
This code is the same as
```
int main()
{
int i,a;
int p, s;
s = scanf("%d %d",&i,&a);
p = printf("PRINT %d\t",s)
printf("%d", p);
return 0;
}
```
scanfreturns the number of items assigned. In your case 2 variables, if successful.
Then you print the string "PRINT 2... |
I'm writing network configuring system for embedded device, which uses ioctl calls.
On starting system I need to check rights to future calls.
Is possible to check enough or have not enough privileges toioctl(ID)call without calling that ioctl?
|
I don't know if this answer to your ask but did you look about capabilities ?
```
if (!CAP_IS_SUPPORTED(CAP_NET_ADMIN)){
EXIT_FAIL("Capability CAP_NET_ADMIN is not supported\n");
}
```
Extracted from man :
```
...
CAP_NET_ADMIN
Perform various network-related operations:
* interface configuration;
... |
I though I had finally understood pointers but then I encountered this issue:
```
typedef struct {
unsigned int a;
unsigned int b;
} Bar;
Bar *foo;
foo->a = 3;
```
This last instruction doesn't work (if I try to access foo->a somewhere else in the code, I either get 0 or rubish)... What am I missing?
|
You need to actually create an object of typeBarand make the pointerfoopoint to it.
```
Bar *foo = malloc(sizeof *foo); // Create a new Bar on the heap
foo->a = 3; // Now it works
```
Or alternately, set the pointer to the address of another object:
```
Bar actualObject; // Create ... |
is control-d a default stop sign for stdin?
In our homework, it says command-d will be stop inputting.
Is it a default ?
|
Ctrl-Don Linux terminal with default settings is an end-of-file marker for stdin.
See alsothe tty demystifiedand thestty(1)command (andtermios(3)...). Use e.g.feof(3)aftersome stdio operation, or compare the result ofgetc(3)withEOF(etc....) to detect end-of-file conditions!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.