question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
if I want ONLY to receive data from a client, and not send data out, is it necessary have a connect() in the code of my server?
Or is it sufficient to have the following?
```
socket();
bind();
listen();
accept();
```
|
This describes the basic principle of server-client interaction. As you can see, the client mustconnectto the server before any interaction.
Once you've built a socket descriptor with the socket() call, you can connect that socket to a remote server using the well-named connect() system call.
Also the sequence you m... |
I want to lock a mutex but fail if a timeout expires. Also I don't want to wait much more after the timeout.
I know what you are thinking.pthread_mutex_timedlock. But if the system clock is changed while it is blocking (e.g. if someone runsdate --setduring the timeout) it can wait for years after (currently up to 44)... |
You are right about the limitation ofpthread_mutex_timedlock(). It's clock is always based on the wall-clock time.
However, this is not true ofpthread_cond_timedwait(). You can modify the attribute of a condition variable so that it usesCLOCK_MONOTONIC(by usingpthread_condattr_setclock()). Your timed lock would actua... |
I am using Monodevelop for unity3d on windows 8 machine. I came to know that I can create a C /C++ project in Monodevelop But when I do not getting a C/C++ option on new solution window when i want to create a new project in C/C++. the options are only Boo, C#, Unity Script and VBnet. Do I need to install external C /... |
The C/C++ plugin of MonoDevelop is only compatible with non-Windows platforms for now.
It'sopensource, so if you have time, you're welcome to fix this situation.
|
I read about the heartbleed exploit and that is was mistake with memcpy.
```
void * memcpy( void * dest, const void *src, size_t len );
```
A proper call to memcpy can look like this
```
int a[4711] [4711];
int b[4711] [4711];
/* initialize a */
(void) memcpy( &b [0] [0], &a [0] [0], sizeof( a ) );
```
But why th... |
If you take a look a the thememcpyManpage, the third argument is the number of bytes that is copied from src to dst. So it doesn't matter if you use the size of src or size of dst. But you must ensure that the source and destination buffer sizes are at least equal or greater than the number of bytes copied. Otherwise,... |
I have a struct
```
typedef struct HASH_NODE
{
char* word;
struct HASH_NODE* next;
} HASH_NODE;
```
and function
```
void foo(char* destptr, const char* srcptr)
{
destptr = malloc(strlen(srcptr)+1);
strcpy(destptr, srcptr);
}
```
I want to pass structs field .word to foo and I expect ... |
You are overwriting the pointerdestptrpassed tofoo()by malloc'ing. Pass a pointer to pointer frommain()tofoo():
```
void foo(char** destptr, const char* srcptr)
{
*destptr = malloc(strlen(srcptr)+1);
strcpy(*destptr, srcptr);
}
```
and call as:
```
foo(&nodeptr->word, word);
```
|
I've been trying to play with execlp() and came up with an idea. I want to execute a man command with more filter. Here is what i came up with:
```
void cmd_help(void)
{
printf("shell command: help\n");
execlp("/usr/bin/man", "man", "intro", "| more -8", NULL);
}
```
It shows the man intro page, but "| more -8" ... |
With execlp you can only execute a single binary file and send some arguments to it. Services like I/O redirection or special char expansions will not work, even if they work on command line. This is because they are performed by shell interpreter before the actual command is invoked. To use them, you will need to inv... |
I am using Monodevelop for unity3d on windows 8 machine. I came to know that I can create a C /C++ project in Monodevelop But when I do not getting a C/C++ option on new solution window when i want to create a new project in C/C++. the options are only Boo, C#, Unity Script and VBnet. Do I need to install external C /... |
The C/C++ plugin of MonoDevelop is only compatible with non-Windows platforms for now.
It'sopensource, so if you have time, you're welcome to fix this situation.
|
I read about the heartbleed exploit and that is was mistake with memcpy.
```
void * memcpy( void * dest, const void *src, size_t len );
```
A proper call to memcpy can look like this
```
int a[4711] [4711];
int b[4711] [4711];
/* initialize a */
(void) memcpy( &b [0] [0], &a [0] [0], sizeof( a ) );
```
But why th... |
If you take a look a the thememcpyManpage, the third argument is the number of bytes that is copied from src to dst. So it doesn't matter if you use the size of src or size of dst. But you must ensure that the source and destination buffer sizes are at least equal or greater than the number of bytes copied. Otherwise,... |
I have a struct
```
typedef struct HASH_NODE
{
char* word;
struct HASH_NODE* next;
} HASH_NODE;
```
and function
```
void foo(char* destptr, const char* srcptr)
{
destptr = malloc(strlen(srcptr)+1);
strcpy(destptr, srcptr);
}
```
I want to pass structs field .word to foo and I expect ... |
You are overwriting the pointerdestptrpassed tofoo()by malloc'ing. Pass a pointer to pointer frommain()tofoo():
```
void foo(char** destptr, const char* srcptr)
{
*destptr = malloc(strlen(srcptr)+1);
strcpy(*destptr, srcptr);
}
```
and call as:
```
foo(&nodeptr->word, word);
```
|
I've been trying to play with execlp() and came up with an idea. I want to execute a man command with more filter. Here is what i came up with:
```
void cmd_help(void)
{
printf("shell command: help\n");
execlp("/usr/bin/man", "man", "intro", "| more -8", NULL);
}
```
It shows the man intro page, but "| more -8" ... |
With execlp you can only execute a single binary file and send some arguments to it. Services like I/O redirection or special char expansions will not work, even if they work on command line. This is because they are performed by shell interpreter before the actual command is invoked. To use them, you will need to inv... |
There are several things I don't understand about the below snippet of code (written in C):
```
struct T {
int a;
int *b;
struct T *next;
} ;
struct T *p1;
struct T* (*f)(int, int, struct T*);
struct T* g(int a, int b, struct T* c)
{
return (a > b ? c : NULL);
}
f = &g;
p1 = (*f)(4,3,p1);
```
In particular, ... |
Linestruct T* (*f)(int, int, struct T*);, Is function pointer,
Where you define pointer to function, Which takes three arguments(int, int, struct T*).
And Codef = &g;means you are assigning function pointerfwith functiong.
|
whenever I call this function it skips over the fgets statement inside it.
```
void getString(char *str){ /* Read a string from the keyboard */
fprintf(stdout,"Please enter a string: ");
fgets(str,MAX_STRING_LEN,stdin);
}
```
here's the function call
```
if(strcmp(cmd,"new")==0){ /* new string command */
... |
You are probably mixing use of scanf() elsewhere in your program and fgets(). Use fgets() for all your input, always to a string, than if necessary use sscanf() to convert the string into other data types.
See the comp.lang.c FAQ which describes this in further detail:
http://c-faq.com/stdio/scanfinterlace.html
|
I am trying to store a string at run time.
```
#include<stdio.h>
#include<string.h>
void main()
{
char string[4];
printf("Enter the String\n");
scanf("%s", &string[4]);
printf("The String entered is %s\t", string);
}
```
Output:
Enter the String
ABCD
The String entered is
B... |
&string[4]is the address of the end of the the array, not the start of it.
Change it to
```
scanf("%s", string);
```
And if you want to hold 4 chars, you need to make it at least with size = 5 (last one is the null termination character):
```
char string[5];
```
|
whenever I call this function it skips over the fgets statement inside it.
```
void getString(char *str){ /* Read a string from the keyboard */
fprintf(stdout,"Please enter a string: ");
fgets(str,MAX_STRING_LEN,stdin);
}
```
here's the function call
```
if(strcmp(cmd,"new")==0){ /* new string command */
... |
You are probably mixing use of scanf() elsewhere in your program and fgets(). Use fgets() for all your input, always to a string, than if necessary use sscanf() to convert the string into other data types.
See the comp.lang.c FAQ which describes this in further detail:
http://c-faq.com/stdio/scanfinterlace.html
|
I am trying to store a string at run time.
```
#include<stdio.h>
#include<string.h>
void main()
{
char string[4];
printf("Enter the String\n");
scanf("%s", &string[4]);
printf("The String entered is %s\t", string);
}
```
Output:
Enter the String
ABCD
The String entered is
B... |
&string[4]is the address of the end of the the array, not the start of it.
Change it to
```
scanf("%s", string);
```
And if you want to hold 4 chars, you need to make it at least with size = 5 (last one is the null termination character):
```
char string[5];
```
|
Is it possible in a linux kernel module to get the pointer of a function exported by another kernel module (something likecat /proc/kallsyms) but with api calls. Also if it would be possbile to load the intended module into memory if it doesn't exist.
Basically what i am trying to do is to introduce a soft dependency ... |
Yes, this is possible. Using following Linux Kernel APIs,
Usingfind_symbolAPI, you can search for desired symbol exists or notIf it fails to find symbol, then you can try to load desired module which exports symbol which you intended to use using APIs calledfind_moduleandrequest_module. Here is sample code for these ... |
Why does a fixed array work but when I try to make it dynamic with malloc it gives a segmentation fault? I've tried all sorts of values besides *10. This is just using a small file. I need this to work with a dictionary of 90,000 words.
```
FILE *fp;
long lSize;
//char buffer[100];
char *buffer=malloc(sizeof(char)*10... |
It should be
```
fscanf(fp, "%s", buffer) //remove the ampersand
```
|
As the title says, would all the pointers be freed after the child dies or do I have to free them manually?
|
Yes,
The OS is a good housekeeper and tidys up for you.
But being a good guest it is better to do it yourself.
Perhaps files need to be closed, network connections tidied up
|
I do not understand the functioning of scanf instruction
```
int i;
scanf("\n");
printf("hello!\n");
scanf("%d",&i);
printf(%d",i);
```
so the the second scanf don't let me type the second input, and it take only the first value why ?
|
when you (for example) input2[space][space][space], the whitespaces will be consumed by\n, even your "enter"! (when you actually want to confirm your input)..
and your2will be stored in variablei..
this\nwill keep scanning until it finds a non-whitespace character, such as:your second int input.. but of course it's n... |
Super basic C program from textbook.
Want to return square ofvalA.
```
int squarer(int valA) {
return valA * valA;
}
int main(int argc, const char * argv[])
{
int valA = 5;
squarer(valA);
printf("\"%d\" squared is \"%d\".\n", valA, squarer);
return 0;
}
```
Code prints"5" squared is "3824".to... |
You just printed theaddressof thesquarerfunction. If you compile with warnings enabled (-Wallor similar), the compiler will tell you this.
The result from callingsquarerisn't stored anywhere: you just threw it out.
If you write
```
int result = squarer(valA);
printf("\"%d\" squared is \"%d\".\n", valA, result);
```... |
Is there any way to call category or test name from code in MSTest during test run?
|
I don't now if it's possible for the test category but you can call the test name using theTestContext.
```
[TestClass]
public class TestClass
{
[TestMethod]
public void TestMethod1()
{
Assert.AreEqual("TestMethod1", TestContext.TestName, "Something went really wrong...");
}
public TestCo... |
OK, so basically, this is what I'm trying to do...
I have a D function like :
```
extern (C) {
void someFunc(string s) {
writeln("Got : " ~ s);
}
}
```
I want to call this from C code with achar*argument.
How is that possible?
|
OK, just found the answer (there was no issue with how it was called, but how I converted thechar *to a D-compatiblestring) :
```
extern (C) {
void myfunc(char* s) {
writeln(to!string(s));
}
}
```
|
Given the following snippet of code:
```
int *iptr;
float *fptr;
float fval;
fval = 0.0;
fptr = &fval;
iptr = fptr;
printf("%d \n", *iptr);
fval = 1.0;
printf("%d \n", *iptr);
```
The output is:
01065353216
Why does the first print statement at least approximately match the value associated with *iptr (0.0), yet t... |
When you writeprintf("%d \n", *iptr);, you are askingprintfto interpret the value pointed to byiptras an integer.
It just so happens thatfloatversion of0is represented by the same bits of theintversion of0. In particular, the bits are all0.
However, an arbitrary float, such as1.0will have a different bit representat... |
This question already has answers here:printf anomaly after "fork()"(3 answers)Closed9 years ago.
The following two codes are compiled and executed using the gcc compiler
code1:
```
main()
{
printf("Before FORK\n");
fork();
printf("After FORK \n\n");
}
```
code 2:
```
main()
{
print... |
stdoutis line-buffered by default when associated with a terminal. In example 2, addfflush(stdout)after the firstprintfto flushstdout.
|
using this code example (dranger - ffmpeg):
https://github.com/arashafiei/dranger-ffmpeg-tuto/blob/master/tutorial03.c
and dranger tutorial for ffmpeg:
http://dranger.com/ffmpeg/tutorial02.html
The video runs as fast as possible but it makes sense because there is no timer and we just extract the frames as soon as... |
Try adding:
```
aCodecCtx = pFormatCtx->streams[audioStream]->codec;
> aCodecCtx->request_sample_fmt = AV_SAMPLE_FMT_S16;
```
|
```
#! bin/bash
CC=gcc
CFLAGS=-I.
DEPS=p.h
%.o: %.c $(DEPS)
$(CC) -c -o $@ $< $(CFLAGS)
hello:p1.o p2.o
gcc hello p1.o p2.o -I.
```
the error showing during the the make of makefile is shown below
```
gcc hello p1.o p2.o -I.
gcc: error: hello: No such file or directory
make: *** [hello] Error 1
```
... |
Changegcc hello p1.o p2.o -I.togcc p1.o p2.o -o hello
|
Why does a fixed array work but when I try to make it dynamic with malloc it gives a segmentation fault? I've tried all sorts of values besides *10. This is just using a small file. I need this to work with a dictionary of 90,000 words.
```
FILE *fp;
long lSize;
//char buffer[100];
char *buffer=malloc(sizeof(char)*10... |
It should be
```
fscanf(fp, "%s", buffer) //remove the ampersand
```
|
As the title says, would all the pointers be freed after the child dies or do I have to free them manually?
|
Yes,
The OS is a good housekeeper and tidys up for you.
But being a good guest it is better to do it yourself.
Perhaps files need to be closed, network connections tidied up
|
I am clearly missing something obvious, but I am stumped:
I have one source file where I declare all of my global variables, and a header file that matches and makes them all extern. However, when I try to use a pragma provided by my IDE (IAR) to data align a variable there, it does not work. It is placing the variab... |
```
data_alignment = expression
```
should give an alignment in bytes, not in multiples of the object size.
So an alignment on 4 bytes boundary is to be expected. It seems everything is ok according to the example addresse you provided
|
I try to compile a library on linux. this libary uses<openssl/sha.h>library. I have included this library in source file. After that, i use flag-lssland flag-lcryptoto compile this project. So here is my command :
gcc -g -Wall -lssl -lcrypto -o bt_client file_a.c file_b.c
But I meet error :
```
undefined reference ... |
Try this:
```
gcc -g -Wall -o bt_client file_a.c file_b.c -lssl -lcrypto
```
If you are sure that symbolSHA1exists inlibssl.soorlibcrypto.so.
|
I want to type in a number that is 10 digits long, then put the digits into an array. But for some reason, I get this random 2-digit numbers that seem to have nothing to do with my input (??).
```
char number[10]; //number containing 10 digits
scanf("%s",number); //store digits of number
printf("%d... |
You are getting ASCII value of characters1and2. Use%cspecifier to print the digits.
```
printf("%c\n",number[0]);
```
|
```
if( ( !valInput(st1,0) ) || (st1[0] < '0') || (st1[0] > 'M-1') )
```
getting a warning: multi character constant
on the M char, and on the '0' ... why?
M is a defined variable replaced in compilation by the number 9\
```
#define M 9
```
my usage is to check whether the first char is by chance smaller than '0' ... |
SinceMis quoted in your code, the preprocessor does not substitute it. (This rule applies to both single and quoted character strings).
Hence the compiler sees'M-1'which is a multi-character constant literal.
If you want to comparest1[0]to the ascii value of '8' then the easiest way is probably to useM - 1 + '0'.
|
I would like to take an array of integers as an input . Even if some one enter a space or an alpahabet, I want to ignore it.
```
int i=0;
while(L--){
scanf("%d",&arr[i++]);
}
```
But if I enter:4 wtfthearr[0]gets initialized to 4 and the loop ends. Is there a way I can ignore everything after a space inscanfand ... |
I think like this?
```
int a;
scanf("%d %*s", &a);
printf("%d\n",a);
```
And
```
input: 11 wwwww
output: 11
```
The*is used to skip an input without putting it in any variable.
|
Is there a way to instruct g++ or clang not to compile out variables that are not being used in the code? I know that most compilers would compile out parts of the code that do not affect the final output. For debugging reasons, I wanted to know if there is a way to disable this?
|
Yes. In gcc (and probably clang, too) you can compile with-O0. This will disable all optimizations. You can also use-Og, which should not remove variables. This flag turns on only the "debugger-friendly" optimizations.
|
I'm trying to use the command:
```
gcc -I${HOME}/usr/include -L${HOME}/usr/lib -lsodium test.c
```
but when I try and run a.out it gives the error:
```
./a.out: error while loading shared libraries: libsodium.so.4: cannot open shared object file: No such file or directory
```
but libsodium.so.4 is definitely in th... |
${HOME}/usr/libis not in your runtime library path.
You can bake the path into your executable using the gcc option-Wl,-rpath,${HOME}/usr/libor set the environment variableLD_LIBRARY_PATH=${HOME}/usr/libbefore executing the program.
ldd a.outwill tell you iflibsodiumcan be found in your runtime library path, and if ... |
I have created a table using avirtual table modulein the sqlite3 front-end.
I do something like:
```
CREATE VIRTUAL TABLE mytable USING mymodule();
```
At which point the module creates a table with--say--3 columns: x, y, and z.
Now when I type:
```
.schema mytable
```
I get this echoed back to me:
```
CREATE V... |
PRAGMA table_infoshould work for this. (According to the documentation, it will not display fields marked "hidden", however)
|
I am clearly missing something obvious, but I am stumped:
I have one source file where I declare all of my global variables, and a header file that matches and makes them all extern. However, when I try to use a pragma provided by my IDE (IAR) to data align a variable there, it does not work. It is placing the variab... |
```
data_alignment = expression
```
should give an alignment in bytes, not in multiples of the object size.
So an alignment on 4 bytes boundary is to be expected. It seems everything is ok according to the example addresse you provided
|
```
#include<stdio.h>
int main(){
int main =22;
printf("%d\n",main);
return 0;
}
```
output:22
I am defining main as function and variable both even though compiler is not giving error. It should give error "error: redefinition of ‘main’ " . I am not able to understand why this code is work... |
It will not give you an error becausemainis not a keyword.but main is define 2 times- Scoping rules come into play.
|
So I created an array and I'm using a For loop to fill the array with values using "scanf". I know i can't use "get()" so scanf appears to be my only option.
```
printf("Enter 4 numbers:");
getchar();
for (i = 0; i < len; i++) {
a[i] = scanf("%d", &input);
}
```
Here is my new code after i have received help on ... |
```
scanf("%d", &input)
```
The above line of code will prompt the user for an input and then add the integer value in input. Now, assigning the above with your a[i] does not make any sense.
What you can do is, instead of using input as a carrier of input, put the input from user directly into your array
```
scanf(... |
```
int arr[10]={1,2,3,4,5,6,7,8,9,10};
printf("%p,%p\n", arr, &arr);
printf("%p,%p\n", arr+1, &arr+1);
return 0;
```
For this code, GCC compiler return
```
0xbfe41348,0xbfe41348
0xbfe4134c,0xbfe41370
```
The first line is clear, no problem. But the second line makes me confused. The first address moves to the next... |
What you think is right and it is done that way only.
Since&arr=>0xbfe41348and
0xbfe41348+0x28(4*10in decimal) =0xbfe41370
I think you got confused due to addition of decimal to a hexadecimal number.
|
I have complied and run the code on a single machine , If I want to run the code on multiple machines in a client server architecture , which file do I place on server and which file do I place on client ?
|
I'm assuming green indicates an executable file and that the file names follow normal naming practices.
Putint_clienton the clients.
Putint_serveron the server(s).
|
In section 6.4.1 of the C11 standard an asterisk appears in the list of keywords:
```
keyword: one of
auto ∗ if unsigned
break inline void
...
```
Does this indicate that*is a keyword?
If not, what is its use here indicating?
|
It is a diff mark.
In the abstract (p.1) ofN1570:
Changes from the previous draft (N1539) are indicated by ‘‘diff marks’’ in the right
margin: deleted text is marked with ‘‘∗’’, new or changed text with ‘‘ ’’.
In theN1539draft,alignofwas a keyword, appearing on the first row of that table:
N1750droppedalignofand... |
I am using a c library which has an API expecting a C function pointer.
Is it possible to pass a C++ class member function for this function pointer?
Here is the C API:
```
typedef int (*WRITE_FUNC_T)(void *d, char *buffer, int n);
void start(WRITE_FUNC_T callback);
class MyClass {
public:
int mycallback(... |
This worked for me:
```
#include <iostream>
#include <sstream>
typedef int (*WRITE_FUNC_T)(void *d, char *buffer, int n);
void start(WRITE_FUNC_T callback) {}
class MyClass {
public:
int mycallback(char *buffer, int n) {
return 0;
}
static int newcallback(void *d, char *buffer, int n) {
return static... |
Can someone help me convert this line to an if-else statement?
temp = head->left ? head->left : head->right;
Thanks!
|
```
if ( head->left )
temp = head->left;
else
temp = head->right;
```
|
I'm a beginner learning learning C for a class at university and was wondering why this piece of code always produce a random number and not 1 like I would expect.
Code:
```
#include<stdio.h>
int main(void){
double a, b = 32.5;
a = 2 / 5 * (b - 30);
printf("%d\n", a);
return 0;
}
```
When I run the... |
You're invokingundefined behaviorby attempting to print a double via the integer format specifier,%d. Use the floating-point specifier instead:
```
printf("%f\n", a);
```
I tired that but it only print 0.000000?
Because of2 / 5-- that performsinteger divisionand thereby results in0. Hence,ais assigned to0. You pr... |
I am creating a shared object which filters the alphanumeric characters it receive from char* buff_in and copy them into char *buff_out, right now my code is doing what I want but it creates ^@ in between the digits.
```
int tratar(char* buff_in, char* buff_out){
int i = 0;
while(buff_in[i]){
if(!isalpha(buff_in[i... |
You need a different index for buff_out:
```
int i = 0, j = 0;
...
buff_out[j++] = buff_in[i];
```
Also, null-terminate buff_out before printf():
```
buff_out[j] = '\0';
```
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question appears to be off-topic becauseit lacks sufficient information to diagnose the problem.Describe your problem in more detail orinclude a minimal examplein the question itself.Closed9 years ago.Improve this q... |
Try the following
```
for(int i =0; i<3; i++)
{
s[i] = ar[i] + '0';
}
```
|
This function is implemented inside my program but when it is called there is an error saying that the variable root is used without being initialized, any reason why?
```
int find(int x)
{
int i, j, root;
for (i = x; parent[i] != i; i = parent[i])
root = i;
/* path compression */
for (i = x;... |
What happens ifparent[x] == x? The neither loop will actually run, because the conditionparent[i] != iwill be false (sincei = x), and thereforerootwill never actually be set to a value.
So, when we returnroot, it's value is undefined, meaning it can beanything.
The easiest way is to setrootto some initial value, say... |
struct node* address; //format <addr,flagBit1,flagBit2>
I want to use BTS toatomicallyset theflagBit1bit.
EDIT
I want to blindly set this bit without caring about if it was previously set or not
I can use assembly code to get this done as suggested inUsing bts assembly instruction with gcc compiler
But is there ... |
For a blind setting of a bit,sync_fetch_and_ororsync_or_and_fetchseem to be both equally good, with the result discarded the compiler knows to optimize it out.
On x86 gcc won't usebts, instead it will simply do alock orwhich should be fine.
|
A segment ofPT_LOADtype, flagsPF_write | PF_read,p_filesiz = xandp_memsiz = x+yit's up to the kernel allocatep_memsiz, correct? How does this allocation actually works? the kernel allocatep_memsizand put the begging of this block memory onp_vaddrso that the write/read memory region of this segment is fromp_vaddrup top... |
Not exactly sure what you are asking, but I can recommend looking into the source code of the dynamic linker, ld.so, which actually loads the ELF objects.
Seethe source code of _dl_map_object_from_fd, have a look at the__mmapinvocations there (one case for relocatable objects, one case for objects that need to be loa... |
I have an input text in a single line of the form "part1 part2". How can i get in 2 different variables part1 and part2 if they have been input in the same line?
|
You can use two different format specifiers :
```
#include <stdio.h>
int main(void)
{
char part1[100],part2[100];
scanf("%99s%99s",part1,part2);
printf("%s,%s\n",part1,part2);
return 0;
}
```
|
```
#include <stdio.h>
int main(void)
{
int i;
int *ptr = (int *) malloc(5 * sizeof(int));
for (i=0; i<5; i++)
*(ptr + i) = i;
printf("%d ", *ptr++);//prin1
printf("%d ", (*ptr)++);//print2
printf("%d ", *ptr);//print3
printf("%d ", *++ptr);//print4
printf("%d ", ++*ptr);//pr... |
*ptr++--> Print0, incrementptrby1.(*ptr)++--> Print1, increment1to2.*ptr--> Print the incremented value stored, i.e2.*++ptr--> Increment theptrby1and then print the value pointed byptr, which is2.++*ptr--> Increment the value , i.e2, pointed byptrand then print it, i.e3.
|
I was reading on wikipedia about thecdeclcalling convention. Since the parameters are pushed on the stack in reverse order, I believe it is safe to call a C function with more parameters than it expects.
Am I right or did I miss something?
Note: I am not talking about variadic functions.
|
I just had a quick look into ISO/IEC 9899 (a.k.a. C99): There's no word about calling conventionsanywhere, thus (as suggested in the comments) you should clearlynot do this. Even if itmightwork on a certain architecture, a certain operating system, and a certain version of a certain compiler, there is absolutelynogu... |
I have my main C file, another C file (which I'm using as a library) and two header files containing the function prototypes for each C file.
How can I compile and link them into one executable file with GCC? I'd like to use the-oand-gflags too.
|
```
gcc -g -c first_file.c
gcc -g -c second_file.c
gcc -o executable first_file.o second_file.o
```
In general though, try googling for agcctutorial first.
|
I try to understand following code:
```
char temp[50];
sprintf(temp,"%04XT1000A",Edit3->Text.ToInt());
```
I know that T1000A is a simple string and I know the meaning of it, but what is %04X? Is %04X completely replaced by the parameter?
|
%04is a format specifier modifier saying that if the output is less than 4 chars it should be padded on the left with0.%Xis standard format specifier meaning print unsigned hexadecimal use capital letters for A-F. Have a look atprintf'sdocumentation.
|
I want to initialise a 2d array having all its elements are 0.
I have tried this:
```
scanf("%d",&n);
int arr[n][n]={0};
```
but i got the [Error]:"variable-sized object may not be initialized"
So,how to do this?
|
Be explicit.
```
#include <string.h>
const int got = scanf("%d", &n);
int arr[n][n];
memset(arr, 0, sizeof arr);
```
Note that ifgotisn't 1, the above has undefined behavior. This is pretty dangerous.
|
I am trying to understand thecairo_scale()function. There is adocumentationbut I still don't get it.
Consider the following code
```
cairo_scale(cr,1./WIDTH,1./HEIGHT);
cairo_move_to(cr,0,0);
cairo_line_to(cr,1,1);
cairo_stroke(cr); //draw a line across the image
```
and (the working version) without scale
```
cai... |
You can think ofcairo_scale()as multiplying all the following coordinates with its argument.
In your case this means you are drawing a line from(0, 0)to(1/width, 1/height)which is less than a pixel.
You want to callcairo_scale(cr, WIDTH, HEIGHT)instead.
|
I want to input an array of integers without giving spaces.
For ex:- 032146548 ,each integer should be stored in array distinctly ,
```
i.e a[0]=0,a[1]=3,a[2]=2 and so on.
```
How can i do this ?
|
I think it's clearer to say "each digit", since it's not at all obvious how many "integers" the character sequence032146548represents (the common practice is "one") once you know it's supposed to be several.
The simplest way is to just read it in as a string of digits, then convert each digit to its integer counterpa... |
I am trying to understand thecairo_scale()function. There is adocumentationbut I still don't get it.
Consider the following code
```
cairo_scale(cr,1./WIDTH,1./HEIGHT);
cairo_move_to(cr,0,0);
cairo_line_to(cr,1,1);
cairo_stroke(cr); //draw a line across the image
```
and (the working version) without scale
```
cai... |
You can think ofcairo_scale()as multiplying all the following coordinates with its argument.
In your case this means you are drawing a line from(0, 0)to(1/width, 1/height)which is less than a pixel.
You want to callcairo_scale(cr, WIDTH, HEIGHT)instead.
|
I want to input an array of integers without giving spaces.
For ex:- 032146548 ,each integer should be stored in array distinctly ,
```
i.e a[0]=0,a[1]=3,a[2]=2 and so on.
```
How can i do this ?
|
I think it's clearer to say "each digit", since it's not at all obvious how many "integers" the character sequence032146548represents (the common practice is "one") once you know it's supposed to be several.
The simplest way is to just read it in as a string of digits, then convert each digit to its integer counterpa... |
```
#!bin/bash
CC=gcc /*gcc compiler*/
CFLAGS=-I. /*current working directory*/
hello: p1.o p2.o p.h /*hello is the executable i want to create*/
$(cc) -o hello p1.o p2.o p.h -I.
```
the error showing is that
```
o hello p1.o p2.o p.h -I.
make: o: Command not found
make: [hello] Error 127 (ignored)
```
by doing... |
make's variables are case-sensitive. You need to write
```
$(CC) -o hello p1.o p2.o p.h -I.
```
Since$(cc)is unset,makewill attempt to execute-o hello .... A leading dash suppresses errors inmakesyntax, so the resulting command is theo hello ...that you see.
|
What is the global id if we had a 2D index space, with work groups of size (14,30). If a particular execution of the kernel in workgroup (2,3) has
```
get_local_id(0) = 5 and get_local_id(1) = 7
```
What would be for get_global_id(0) and get_global_id(1) ? I actually do not have the local size!
How can we calculate... |
You need to know the local size. And thankfully you can get it by calling get_local_size. It will always return a valid value.
It goes like this assuming no offset:
```
get_global_id(0) = get_local_id(0)+get_local_size(0)*get_group_id(0)
```
Remember that even if you call your kernel with NULL as the local size the... |
This question already has answers here:C++ global and local variables(8 answers)Closed9 years ago.
If i compile and run the following code, it is printing 0 instead of 10.
```
#include<stdio.h>
main()
{
int Var=10;
{
char Var=Var;
printf("%d",Var);
}
}
```
Why this is printing 0 and why not 10 ?... |
Because in local declaration
```
char Var=Var;
```
the right occurrence ofVarrefers to the localVar, not the upper one. AsAlkcommented, this isundefined behaviorto assign from an uninitialized variable.
So your declaration does not initializeVarat all, i.e.Varcontains garbage. In your particular case, that garbage ... |
There are two variables,
```
uint8_t x (8 bit type)
uint16_t y (16 bit type)
```
, that together hold information about the value of an intnum. Saynumconsists of four bytesabcd(where a is most significant). Then x needs to be copied to b, and y needs to be compied to cd. What is the best way/code to do this?
|
This works for me:
```
#include <stdio.h>
#include <stdint.h>
int main()
{
uint8_t x = 0xF2;
uint16_t y = 0x1234;
int a = 0x87654321;
// The core operations that put x and y in a.
a = (a & 0xFF000000) | (x<<16);
a = (a & 0xFFFF0000) | y;
printf("x: %X\n", x);
printf("y: %X\n", y);
printf... |
I saw that MinGW has a makefile too which is not supported in NetBeans/Eclipse. Why? And why MSYS? I also heard MSYS is Unix like env, so why do I need it for Windows programming?
|
Simply put msys is a unix/linux like enviorenment on windows. means you can run your program in unix/linux which you're making on windows
|
I am super beginner to C and I was wondering if these variables are being passed properly, I'd like their values to be altered in main. I'm mainly wondering if I am using & and * properly.
```
#include <stdio.h>
int assign(int *i, int *scores[]);
int main(void){
int scores[30], i;
assign(&i, &scores[0]);
... |
You're passing far too many levels of indirection:
```
#include <stdio.h>
void assign(int *scores);
int main() {
int scores[30];
assign(scores);
return 0;
}
void assign(int *scores) {
int i;
printf("Input scores:\n");
for (i = 0; i < 30; i++) {
scanf("%d", &scores[i]);
}
}
```
|
Newbie in C programming.In gcc-stdsets the C standard that compiles, e.g.gcc -std=c99.It's possible to know which C standard is currently set?
|
There are various preprocessor symbols that are defined in various modes. You can usegcc -E -dM -x c /dev/nullto get a dump of all the preprocessor symbols that are predefined.
When in C99 mode (-std=c99or-std=gnu99), the symbol__STDC_VERSION__is defined to be199901L. In C11 mode (with-std=c11orstd=gnu11), it's2011... |
A simple code like this,
```
int arr[3][3] = {1, 2, 3, 4};
printf("%d\n", *(arr));
```
I thought the output would be the first value of table, 1, but gcc returns me a garbage value.
Can anyone explain the difference between multiple dimension table and simple table?
|
You got the address of the first row of the array, which is also the address of the first element of the entire array.
*(arr)is equal toarr[0]
Therefore you are trying to print an address and should use a %p printf specifier.
|
This question already has answers here:Why is the asterisk before the variable name, rather than after the type?(13 answers)Closed9 years ago.
Ischar* myStringorchar *myStringconsidered best practice? My professor consistently useschar* myStringand this seems to be less confusing thanchar *myString, but I've also see... |
Some preferchar *myStringbecause the pointer is not "distributive". That is:
```
char* str1, str2;
// Is equivalent to:
char* str1; // or char *str1;
char str2; // Note, not a pointer
```
By defining them in this way:
```
char *str1, str2;
```
it is more clear that one is a pointer and one is not. Also note, som... |
This question already has answers here:C - What is this syntax about? <<(6 answers)Closed9 years ago.
I am reading a tutorial in objective - C but it uses some things of C / C++. I've this line of code:
```
static const uint32_t projectileCategory = 0x1 << 1;
```
So I want to know why does the variable equals ... |
This is called a leftbit shiftwhich is a bitwise operation, and is equivalent to your second example.
0x1 << 1shifts the bits of value0x11 to the left, which produces two.
```
0x1: 00000001
0x2: 00000010 <- product of 0x1 << 1
0x4: 00000100 <- product of 0x1 << 2
```
|
Im writing a hexdump function in C.
How can I truncate a given address (void* start) to the greatest multiple of 16 that's less than the given start argument?
Is there a simple way to do this?
Thanks
|
```
uintptr_t rounded = ((uintptr_t)start) & ~0xF;
```
|
I'm using Eclipse C/C++ IDE with MinGW to run and debug my aplications.
When I run it works fine but when I debug my application crash
Here is my code:
```
#include <windows.h>
#include <stdio.h>
void loadDLL() {
int handle = LoadLibrary("teste.dll");
printf(handle == 0 ? "\n DLL not loaded." : "\n ... |
My friend found the solution of the problem!
I needed ouncheckan option at my application launcher.
The option isLoad shared library symbols automaticallyat:
AppLauncher >> Debugger >> Shares Libraries
|
I was wondering how to include files like LUA scripts, dlls, ect in a code:blocks build (debug and release) or would I just have to copy over all the files manually to the folders?
|
As far as I know, it is done by manual organization
|
I've been stumped over this one:
SpanLogger_c.h
```
#ifndef SPANLOGGERCH
#define SPANLOGGERCH
struct CSpan
{
int64_t trace_id;
};
#endif
```
main.c
```
#include "SpanLogger_c.h"
int main(int argc, char * const argv[]) {
struct CSpan span;
}
```
compilation command:
```
g++ -g -I. main.c
```
I get this ... |
In SpanLogger_c.h:
```
#include <stdint.h>
```
If you're intending to write C++ use:
```
#include <cstdint>
```
|
Ok, so I have an array of srings
```
char array[4][20];
//initialized
strcpy(array[0], "PERSON1");
strcpy(array[1], "PERSON2");
...
```
My question is how would I use shmget, and shmat to turn this array into shared memory?
Any help appreciated!
|
```
int segment_id = shmget(IPC_PRIVATE, sizeof(array),0660 | IPC_CREAT);
char** shared = shmat(segment_id,NULL,0);
```
This is a possible solution.
|
I'm in an introductory course and I am curious about casting with pointers.
What would be the difference between:
```
*(uint32_t*)(p)
(uint32_t)(*p)
```
pis a pointer.
|
```
*(uint32_t*)(p)
```
Extracts 32 unsigned bits at the memory location.
```
(uint32_t)(*p)
```
Extracts p from the memory location in its native type, and cast that type to a 32 bit unsigned int.
The results will probably be most notable if p is a floating point type. When extracted the first way you can see the... |
I thought at the end of the programme, il will print 3 but in fact it is 0.
Can anyone explain how it is happening ?
Here is the code :
```
int arr[3] = {2, 3, 4};
char *p;
p = arr;
p = (char*)((int*)(p)); // two conversion, means nothing, omit
printf("%d, ", *p); // point to 2,
p = (int*)(p+1); // point to 3... |
You are treating an array of integers like an array of chars. The line that is marked as "means nothing" actually means a lot.
When you incrementchar* pby one, you shift your pointer one byte, but in order to point to thearr[1]you need to increment itsizeof(int)bytes. Declarepasint* p, thenp+1will do what you need.
|
This is the code that make me confused.
```
static char *s[] = {"black", "white", "pink", "violet"};
char **ptr[] = {s+3, s+2, s+1, s}, ***p;
p = ptr; // p point to the address of (s+3), so "violet"
++p; // p point to "pink"
printf("%s", **p+1); // I though it print "pink" but answer is "ink", I'm not sure about ... |
After++p,pdoes not point to "pink". It points toptr[1], andptr[1]points tos[2], ands[2]points to the first character of "pink".
*pisptr[1], and**piss[2]. So**p + 1is&s[2][1], i.e. the "i" in "pink".
It is like:
```
char *ptr = **p; // ptr points to the 'p' in "pink"
printf("%s", ptr + 1);
```
|
From the kernel 3.4code,I could not make out that where the UART Base address is mapped ?As far as I know for mapping the base address we should userequest_mem_regionandio_remapfunction.But I could not find this in the code.Base address for UART4 is 0x4806E000
|
This should be defined in the dts file in arch/arm/boot/dts/omap4.dtsi file. I'm not sure if DT is enabled for your kernel.If enabled, it reads in the probe function
|
Are the following to equivalent:
```
#define xxx
```
in source and
```
gcc -D xxx
```
Does the first one only apply to the source file where it appears and not in other source files where it doesn't appear, so that xxx is not defined in those other files?
Does the second one imply that xxx is defined in all sourc... |
Does the first one only apply to the source file where it appears and
not in other source files where it doesn't appear, so that xxx is not
defined in those other files?
Right.
Does the second one imply that xxx is defined in all source code
files?
Yes
Both methods do same things but scope of that definat... |
I was wondering how to include files like LUA scripts, dlls, ect in a code:blocks build (debug and release) or would I just have to copy over all the files manually to the folders?
|
As far as I know, it is done by manual organization
|
I've been stumped over this one:
SpanLogger_c.h
```
#ifndef SPANLOGGERCH
#define SPANLOGGERCH
struct CSpan
{
int64_t trace_id;
};
#endif
```
main.c
```
#include "SpanLogger_c.h"
int main(int argc, char * const argv[]) {
struct CSpan span;
}
```
compilation command:
```
g++ -g -I. main.c
```
I get this ... |
In SpanLogger_c.h:
```
#include <stdint.h>
```
If you're intending to write C++ use:
```
#include <cstdint>
```
|
Ok, so I have an array of srings
```
char array[4][20];
//initialized
strcpy(array[0], "PERSON1");
strcpy(array[1], "PERSON2");
...
```
My question is how would I use shmget, and shmat to turn this array into shared memory?
Any help appreciated!
|
```
int segment_id = shmget(IPC_PRIVATE, sizeof(array),0660 | IPC_CREAT);
char** shared = shmat(segment_id,NULL,0);
```
This is a possible solution.
|
I'm in an introductory course and I am curious about casting with pointers.
What would be the difference between:
```
*(uint32_t*)(p)
(uint32_t)(*p)
```
pis a pointer.
|
```
*(uint32_t*)(p)
```
Extracts 32 unsigned bits at the memory location.
```
(uint32_t)(*p)
```
Extracts p from the memory location in its native type, and cast that type to a 32 bit unsigned int.
The results will probably be most notable if p is a floating point type. When extracted the first way you can see the... |
I was wondering whether it would be legit to allocate a buffer for stdio stream buffering and use it withsetvbuf(beforefork), where the buffer is an anonymousmmap-"allocated" piece of memory shared between parent and child process?
Assuming the two are synchronized, am I allowed to assume that the outcome will be som... |
You should not do this. Your C library will assume that theprocesshas exclusive access to the standard IO buffer area, and will only mediate betweenthreadsof that process, no doubt using a mutex not in anonymousmmap. So you risk undefined behaviour if that buffer space is altered, just as if you wrote over it yourself... |
The code below is related to calculating length of string
```
#include <stdio.h>
int strl (char *s);
main ()
{
int len1 = str ("hah");
printf ("%d", len1);
}
int
str (char *s)
{
int length = 0;
while (*s != '\0')
{
length++;
s++;
}
return (length);
}
```
When I call the functionstr,... |
"hah"is oftypechar[]so when you pass it to function, it decays to pointer to its first element, as any other array.
|
Question
How would I change the least significant bit to 0 without affecting the rest of the value, for example:0xffffffff, for example in C or Python? I am not a mathematical genius, so for me it's a hassle to find out how to achieve this.
Solution
```
n = 0 // clear this bit
0xffffffff &= ~(1U << n) = 0xfffffffe
... |
Try this to clear the least significant bit:
```
int x = 0xffffffff;
...
/* clear least significant bit */
x &= ~1;
```
To set the LSB
```
int x = 0xffffffff;
...
/* set least significant bit */
x |= 1;
```
To change the LSB
```
int x = 0xffffffff;
...
/* change least significant bit */
x ^= 1;
```
If you ... |
I have an exam question question here which asks:
"The C operator -> is a shorthand for a more complex notation. Explain the circumstances in which -> or the more complex notation would be used. Write an example of the more complex notation."
I`m not sure what the examiner is looking for here. My impression is that ... |
Dereferencing can be done either by using->or(*).. See the example
```
struct point {
int x;
int y;
};
struct point my_point = { 3, 7 };
struct point *p = &my_point; /* To declare and define p as a pointer of type struct point,
and initialize it with the address of my_point. */
... |
Conceptual question. Consider the following code:
```
#include<stdio.h>
int brasa(int, float);
int brasa(int, int);
float brasa(int, int);
int main(){
return 0;
}
```
The compiler gives the following errors:
```
Line 4: error: conflicting types for 'brasa'
Line 3: note: previous declaration of 'brasa' was here... |
In C you can't declare a variable/functionmultiple timeswith different types (incompatible types). There is no function overloading, unlike in C++, in C.
|
why would the second line
```
int i=-3, j=2, k=0, m;
m = ++i && ++j || ++k;
```
terminate after++jand ignore++k?
I know the first half make TRUE value and would return TRUE whatever the following value is. But what is the condition to stop executing following instrument? As long as we can confirm the final value?
|
&&has higher precedence than that of||.++iand++jbinds to it and
```
m = ++i && ++j || ++k;
```
is parsed as
```
m = (++i && ++j) || ++k;
```
Since both the sub-expressions++iand++jare non zero, it is interpreted astrue. Due to short circuit behavior of logical operators second (right) sub-expression is not evaluat... |
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.Closed9 years ago.Improve this question
I want to convert binary number to octal directly without converting into base 10, I foun... |
Converting binary to octal (and vice-versa) is fairly easy because 2^3=8.
This means you only need to go from least significant bits to most significant bits, and 'translate' each group of 3 bits to its respective number.
Example:
101 100 110:
```
110 -> 6
100 -> 4
101 -> 5
```
Translation to octal is now simply... |
I'm working on an Applescript droplet that will clang any source file I drop on it.
The only real line I have in it is
```
do shell script "clang " & (POSIX path of this_item as text)
```
However I get the error
ld can't open output file for writing: a.out, errno=13 for architecture x86_64
This doesn't happen whe... |
Have you tried..
```
quoted form of (POSIX path of this_item as text)
```
|
Can anyone explain me why this line of code is wrong?
```
int n = 0, y = 1;
y == 1 ? n = 0 : n = 1;
```
The error is"Lvalue required as left operand of assignment "for"n=1"
|
The statement
```
(y == 1 ? n = 0 : n) = 1;
```
is interpreted as becausenbinds with?:operator due to its higher precedence.=needs l-value as its left operand while?:returns an r-value.Try this instead
```
y == 1 ? n = 0 : (n = 1);
```
or
```
n = y == 1 ? 0 : 1;
```
|
I'm trying to use the hardware instructions to compute some mathematical functions. For example the square root (sqrtpd instruction). I'm compiling my C code with GCC.
Does Anybody know what are the gcc options to force to compile with the hardware instructions and not to use the libc? Or if I need to do something sp... |
On gcc you should use__builtin_ia32_sqrtpd.
|
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question
I am working on mobile communication Simulator based on C language. I have two different IPs which are stor... |
```
#include <string.h>
...
for ( int i = 0; i < num_users; i++ )
{
if ( strcmp( ABC[i], XYZ ) == 0 )
{
// strings are equal
}
else
{
// strings are not equal
}
}
```
ABC[i]is thei'th string stored inABC.
|
I have a struct abc in one file
```
struct abc {
some variaables
and functions
}
```
I am using this struct in other file as follows :struct abc *t = kmalloc(sizeof(struct abc));kmalloc is equivalent to malloc
then following errors occur:
```
expected '=', ',', ';', 'asm' or '__attribute__' before 'struct'... |
1, 2, 4 and 5 errors are caused by missing;at the end of your struct declaration. It must be:
struct abc {
some variaables
and functions
};
3 error is caused by missing the including ofinclude/linux/slab.hfile. You have to add the below file at the head of your source code file:
#include < linux/slab.h># pl... |
Given the method header
```
void scanArray(void *arr, int const numElements, int const sizeElement, char const *fmt)
```
where*arrcan be any type ofarray,numElementsis the number of elements in the array, andsizeElementis the size of the type of value in the array, andfmtis a string such as%d,%lf, or%f, how would yo... |
```
void scanArray(void *arr, int const numElements, int const sizeElement, char const *fmt){
int i;
unsigned char *tempArr = (unsigned char*) arr;
for(i=0; i<numElements; i++, tempArr+=sizeElement) scanf(fmt, tempArr);
}
```
This seems to be working for me...
|
Consider,
```
#include<stdio.h>
int main()
{
int y = facto(6);
printf("%d",y);
return 0;
}
int facto(int x)
{
if(x==1)
return 1;
else
return x*facto(x-1);
}
```
I read in some posts which said that calling a function before it is defined is an implicit declar... |
y=facto(6)is an implicit declaration because you're telling the compiler "I want to call a function and pass a single int, so somewhere down the road there will be a function with a single int parameter."
If the compiler ran into theint facto(int x)first, then that's the explicit declaration.
Implicit declarations a... |
I am aware of what the ceil function does, it rounds numbers up.
So; 1.3 to 2.0 and 5.9 to 6.0.
But I want it to round up with steps of 0.5.
So; 1.3 to 1.5 and 5.9 to 6.0.
Is this possible?
Thanks!!!
|
```
y = ceil(x * 2.0)/2.0;
```
should do what you need:
```
x x*2.0 ceil(x*2.0) y
------------------------------
1.3 2.6 3.0 1.5
1.6 3.2 4.0 2.0
5.9 11.8 12.0 6.0
```
|
Sorry for being such a dumb here. Can't sort this out for myself.
In a header file there is a Macro like this.
```
#define kOID "1.3.6.1.4.1.1.1.2.4.0"
```
How to declare and initialize a char pointer to this data without creating a copy of this string?
|
Preprocessor macros are nothing but a textual substitution. Thus if you write
```
const char *pointer = kOID;
```
the preprocessor will substitute the text with
```
const char *pointer = "1.3.6.1.4.1.1.1.2.4.0";
```
One thing to bear in mind is that theconstspecifier is necessary since once the textual substitutio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.