question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I have an array of objects each object has some data members in it.All i want do is create a file for each object to store data.Is this possible? For example i have an array of 10 objects data of the first object must be stored in data01.txt data of second object must is stored in data02.txt and etc (same format of fi... |
You have to write just one function:
```
std::string serializeObject(const XClass &object);
```
Which will represent object's data as a string.
And then write serialized objects to files routinely:
```
std::ofstream outFile;
for (...
outFile.open(sFileName);
outFile << serializeObject(..
```
|
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 have created a program in c++ and now i wish to run it on my blog.Is this possible? If ... |
ThisCGI C/C++ Tutorialmight be of help.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed9 years ago.Improve this question
When I run this program in the Nios 2 simulator I get the expected output (1.00000... |
Declarenas
```
float n=0.0f;
```
it will work.
|
In the below code, if there is a problem creating a child process or something happens to the child process what happens towait(&status)?
```
pid_t pid;
int status;
if(pid=fork()){
printf("Parent Process\n");
wait(&status);
} else... child process here
```
|
If there is a problem creating a child process, fork will return-1, so this code will neverwait.
If there's something happend to the child process, wait will return, and you can observestatus.
|
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
In the Samsung R&D placement test a question was there:
What's the maximum size allocated... |
This is a nonsense question, as it is highly system-dependent. None of the answers is right; there are system where you cancalloc()mega- and gigabytes of memory.
|
I have the following text:
```
ASDCASDSA255878 Jack Jhon 1988 12
ASDCASDSA255878 Bill Smith 1977 12
```
And i have the following code:
```
inputFile = fopen(fileName,"r");
char id[50];
char fname[50];
char lname[50];
char year[50];
char month[50];
while(fscanf(inputFile, "%s %s %s %s %s\n",id,fname,lname,year,month... |
Most probably the words in the input are longer than 50 characters.
The easiest way to check this is to temporarily change all occurrences of[50]in your code to the input file size, so it will be large enough.
|
hello im trying to add a space between two strings and strcopy them into a variable
in php we could just add them with a +
```
front_name = "hello";
back_name = "world";
full_name = strcpy(m[index].p.something, front_name + " " + backname);
// should output hello world
```
what is the equivalent or the right way to... |
sprintf would be ideal provided the buffer that the strings are copied to is large anough:
e.g.
```
char buffer[512];
sprintf(buffer, "%s %s", front_name, backname);
```
|
First, I know that when copying a file, if thebuffer sizeis bigger, the copying process will be faster.
The followingrubyscript used to write line-by-line (i.e. size of buffer will depends on the line length):
```
input,output = ARGV[0], ARGV[1]
f_in = File.open input, "r"
f_out = File.open output, "w"
f_in.each {... |
It's probably due disk caches, try running
echo 3 > /proc/sys/vm/drop_caches
to clear up the cache before running your benchmark :)
my guess is that they do should be very, very close, ofcourse cp should start copying some miliseconds faster than ruby.
|
I have a very simpleMakefilewhich is supposed to do the same task asgcc -o mysh mysh.c -Wallbut I am receivingmake: Circular mysh <- mysh dependency dropped.however the executable is created and works fine. Do you know how to remove this message?
```
C=gcc
CFLAGS=-Wall
all: mysh
mysh: mysh
${C} ${CFLAGS} -o ... |
Change
```
mysh: mysh
```
into
```
mysh: mysh.c
```
That should do it.
You hadmyshdependent onmyshwhich is a circular dependency.
|
I have created a shell and when I give wrong number of arguments like insufficient arguments tocpcommands I receive the Linux shell error message like what you will receive if you typecp fork.cas follows:
```
mysh> cp fork.c
cp: missing destination file operand after `fork.c'
Try `cp --help' for more information.
```... |
```
cp fork.c > /dev/null 2>&1 || echo "Dude! this is an error"
```
|
So far, I have that if the filename argument (fname) is left empty, the program readsstdinautomatically.
```
if (!strcmp(fname, ""))
fin = stdin;
```
But I need to know whether thatstdinwas piped in, or interactive, because I could possibly get something like:
```
rsm: reading from (stdin)
^Z
rsm:(stdin):1: not... |
On Posix systems, you can useisatty:
```
#include <stdio.h>
#include <unistd.h>
if (isatty(STDIN_FILENO))
{
// interactive stdin
}
```
On Windows, you can use the corresponding function_isatty.
|
Consider the following code, with various#definestatements;
```
#define PUSH 0x50
#define POP 0x58
#define NOP 0x90
#define JUNK __asm__(PUSH, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, POP)
#define J 0.752
#define L 27
```
The first few states define some HEX values which are assembly instructions, and then a g... |
These are not "memory definitions". They are preprocessor macros. The compiler itself has no visibility of them, as they're all substituted (essentially by copy-and-paste) before it runs.
|
c
I want to use fscanf to read in a file in the following format.
```
//text file
push i
push o
pop
push i
pop
push a
```
a word then a character seperated by a space. Then assign the word to a pointer or var and the same for the char. but I keep getting a segmentation fault error.
```
FILE * fp("text.txt", ... |
The pointerdatais uninitialized, so whenfscanfattempts to dereference it, you get the segfault.
What you should do is just declare it as just achar(not achar *), and change the lastfscanfparameter to&data:
```
while(fscanf(fp, "%s %c[^\n]", word, &data) != EOF) {
^
```
Also, the... |
I am trying to count how many times a.appear in a single string passed in by the command line.
callingmyprog "this...is a test."
returnsThe count is 0?
What am I doing wrong here?
Note:I know this code may look odd but is for education purposes
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int m... |
You are counting the number of commas, not of periods. To count periods change the if statement to:
```
if (*p =='.'){
count++;
}
```
|
How can I define such a Lua function using C API?
```
function Caller(f)
f()
end
```
This is what I've tried but it crashes:
```
typedef lua_CFunction luaFunc;
int Caller(lua_State* luaVM)
luaFunc Func = lua_tocfunction(luaVM, 1);
lua_pushcfunction(luaVM, Func);
lua_call(luaVM, 0, 0);
return 0... |
The equivalent of the Lua code
```
function Caller(f)
f()
end
```
is
```
int Caller(lua_State* luaVM)
lua_call(luaVM, 0, 0);
return 0;
}
```
|
I have an array of objects each object has some data members in it.All i want do is create a file for each object to store data.Is this possible? For example i have an array of 10 objects data of the first object must be stored in data01.txt data of second object must is stored in data02.txt and etc (same format of fi... |
You have to write just one function:
```
std::string serializeObject(const XClass &object);
```
Which will represent object's data as a string.
And then write serialized objects to files routinely:
```
std::ofstream outFile;
for (...
outFile.open(sFileName);
outFile << serializeObject(..
```
|
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 have created a program in c++ and now i wish to run it on my blog.Is this possible? If ... |
ThisCGI C/C++ Tutorialmight be of help.
|
I have came across this interview question. I know it's tricky but can't think of any approach.
Change the program so that the output of printf is always20. Onlyfoo()can be changed.main()function can not be changed.
```
void foo()
{
// Add Here
}
int main()
{
int i = 20;
foo();
... |
We can use Macro Arguments to change the output of printf.
```
void foo()
{
#define printf(x, y) printf(x, 20);
}
int main()
{
int i = 20;
foo();
i = 100;
printf("%d", i);
return 0;
}
```
By using this, duringprintf("%d",i)will get mapped to macro expansionprintf("%d",20)
|
I was going through some c code and came across this syntax:
```
uint16 a;
unsigned char *b;
//b is initilized elsewhere before the next line gets called
((unsigned char*) &a)[0] = b[0];
```
It the last line which I dont get. We typecast the address of uint16 to a unsigned char. Why is this? The address of &a could ... |
You're taking the address ofa, cast it tounsigned char*(notunsigned char), add 0 to it (no op), dereference it and then assign the result ofb[0]to it. In other words, you're assigning the result ofb[0]to the first byte ofa's in-memory representation.
Sincebhas not been initialized this invokes undefined behavior.
|
In my programming class we are not allowed to use || && and ! for this assignment. How can you do a "not" statement without the use of !? Also, how to do && would be useful but I think I can figure it out.
(we can use % / * pow abs ln + -)
|
!ais equivalent to1-a, providedais guaranteed to take only the values 0 or 1.
|
I have achar* linefromfgets (line , 255 , pFile)that I want to add the character "#" to the end of. How do I do this in c++?
Something like
```
while ( fgets (line , 255 , pFile) != NULL )
{
line = line + '#'
}
```
|
```
strcat(line, "#");
```
Of course the correct answer is to usestd::stringinstead.
|
Currently i'm having the problem, that if I send a buffer, it may be send only partially and return the count of bytes sent. Is there any way to set some option or sth. that prevents the bsd socket from sending partially?
|
Generally there is no way to do this withSOCK_STREAMsocket types such as TCP.SOCK_DATAGRAM(for IP, this means UDP) andSOCK_SEQPACKET(for IP, there is no such thing) would do what you want, but with different limitations of their own.
In any case, the solution is that you need to do your own data buffering and framing... |
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ... |
You may try like this for32 bit int:-
```
(x >> 31) | (((~x + 1) >> 31) & 1)
```
|
How can i remove thegotofrom the following code?
```
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
bool is_prime(unsigned num)
{
if(num==0 || num==1)
return false;
if(num==2)
return true;
for(unsigned i=2;i<=num-1;i++)
if(num%i==0)
goto step;
return true;
... |
Replace it withreturn false;.returnexits a function. The code even relies on that behaviour already.
```
bool is_prime(unsigned num)
{
if(num == 0 || num == 1)
return false;
for(int i = 2; i < num - 1; i++)
if(num % i == 0)
return false;
return true;
}
```
|
I have a long binary string which contains a number of bytes,
I need to usefseekto get to a specific byte in the string.
I know I need to calculate the offset but I'm not sure if the offset
is calculated by bits or bytes. If I need to get to the 3rd byte for example
I need to advance the indicator by 3 or by (3*8=)24... |
fseektakes offset as the number of bytes, not bits:
The new position,measured in bytesfrom the beginning of the file, shall be obtained by adding offset to the position specified by whence. (emphasis is mine).
|
I was wondering, why is casting implicitly from an integer to a char possible in C ?
If for example :
```
int i = 2789;
printf("%c\n",i);
```
would give me a char back, because it would have truncated the bits starting from the most significant ones.
But usually you can't really cast implicitly if it means you'll ... |
There is no implicit cast going on here.
printfis avariadicfunction, which means that any arguments of typecharare converted up tointbefore the function is called. Your argument is already of typeint, so no conversion occurs.
|
```
#include <stdio.h>
int main()
{
printf(5 + "abhishekdas\n") ;
return 0 ;
}
```
The output of the program ishekdas. How is it working? Shouldn't it show error? How is it possible to write something like5 + "abhishekdas"insideprintffunction ?
|
```
5+"abhishekdas\n" ==> "abhishekdas\n"+5 ==> &"abhishekdas\n"[5] ==> "hekdas\n"
```
|
How to convert a 32-bit integer value to an ip-address?
I am havingint value=570534080and want to convert it to192.168.1.34.
|
```
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(void) {
int value=570534080;
struct in_addr addr = {value};
printf( "%s", inet_ntoa( addr ) );
return 0;
}
```
Test:http://ideone.com/RCDgj4
For Windows use#include <winsock2.h>
|
This produces the incorrect output.
Can someone tell me what I am doing wrong. The first 1,2 or 3 characters are displayed (depending on the chars) but the rest are random.
Note:This is just a learning exercise & am aware there are easier ways to do this.
```
int main(int argc, char *argv[])
{
//Assume 1 arg only... |
you should usesizeof(char)which equals to1; try this:
```
j = sizeof(char);
for (k = 0; k < len; k++ ) {
printf("Value: %c\n\n", *(x + k * j)); // j equals to 1
}
```
Note:*(a + b)equals toa[b]orb[a]
|
I have doubt with reference to the execution of wait_event_interruptible and wake_up_interruptible.
Doubt 1: Suppose in wait_event_interruptible condition was made TRUE in that case Process state is directly changed to RUNNING state?
If Yes in that case is it not required to call wake_up ? What is the use of wake up... |
When the condition is already true, there is no need to wait.(Thewait_event* functions check the condition also before they begin the actual wait.)When the condition is still false, it will go back to sleep.
|
I'm trying to look into a piece of code, and something confused me.
When we use structure below:
```
struct sdshdr {
int len;
int free;
char buf[];
};
```
We will allocate memory like this:
```
struct sdshdr *sh;
sh = zmalloc(sizeof(struct sdshdr)+initlen+1);
```
So, what's the dif... |
The difference is simplechar buf[]declares a flexible array;char * bufdeclares a pointer. Arrays and pointers are just not the same, in many ways. For instance, you'll be able to assign directly to a pointer member after initialization, but not to an array member (you'll be able to assign to the entire struct).
|
```
#include <stdio.h>
int main()
{
printf(5 + "abhishekdas\n") ;
return 0 ;
}
```
The output of the program ishekdas. How is it working? Shouldn't it show error? How is it possible to write something like5 + "abhishekdas"insideprintffunction ?
|
```
5+"abhishekdas\n" ==> "abhishekdas\n"+5 ==> &"abhishekdas\n"[5] ==> "hekdas\n"
```
|
How to convert a 32-bit integer value to an ip-address?
I am havingint value=570534080and want to convert it to192.168.1.34.
|
```
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(void) {
int value=570534080;
struct in_addr addr = {value};
printf( "%s", inet_ntoa( addr ) );
return 0;
}
```
Test:http://ideone.com/RCDgj4
For Windows use#include <winsock2.h>
|
This produces the incorrect output.
Can someone tell me what I am doing wrong. The first 1,2 or 3 characters are displayed (depending on the chars) but the rest are random.
Note:This is just a learning exercise & am aware there are easier ways to do this.
```
int main(int argc, char *argv[])
{
//Assume 1 arg only... |
you should usesizeof(char)which equals to1; try this:
```
j = sizeof(char);
for (k = 0; k < len; k++ ) {
printf("Value: %c\n\n", *(x + k * j)); // j equals to 1
}
```
Note:*(a + b)equals toa[b]orb[a]
|
I have doubt with reference to the execution of wait_event_interruptible and wake_up_interruptible.
Doubt 1: Suppose in wait_event_interruptible condition was made TRUE in that case Process state is directly changed to RUNNING state?
If Yes in that case is it not required to call wake_up ? What is the use of wake up... |
When the condition is already true, there is no need to wait.(Thewait_event* functions check the condition also before they begin the actual wait.)When the condition is still false, it will go back to sleep.
|
I'm trying to look into a piece of code, and something confused me.
When we use structure below:
```
struct sdshdr {
int len;
int free;
char buf[];
};
```
We will allocate memory like this:
```
struct sdshdr *sh;
sh = zmalloc(sizeof(struct sdshdr)+initlen+1);
```
So, what's the dif... |
The difference is simplechar buf[]declares a flexible array;char * bufdeclares a pointer. Arrays and pointers are just not the same, in many ways. For instance, you'll be able to assign directly to a pointer member after initialization, but not to an array member (you'll be able to assign to the entire struct).
|
I am trying to print each char in a variable.
I can print the ANSI char number by changing to thisprintf("Value: %d\n", d[i]);but am failing to actually print the string character itself.
What I am doing wrong here?
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
... |
You should use%cformat to print characters in C. You are using%s, which requires to use pointer to the string, but in your case you are providing integer instead of pointer.
|
How can I copy a command line arg to a variable inc? If was to do the following.
myprog "Hello, world!"
I want to store the value of the parameter in acharvariable. Not sure if I am going in the right direction here.
Assuming only 1 parameter will be passed in always.
```
int main (int argc, char *argv[]){
int... |
If you're not planning to manipulate the argument, you could just copy the pointer, like this:
```
int main(int argc, char* argv[]) {
char* array;
array = argv[1];
...
}
```
Otherwise, you can make a copy of the string like this:
```
int main(int argc, char* argv[]) {
char* array;
array = str... |
```
char ch;
while((ch = getchar()) != EOF){
putchar(ch);
}
```
The above code, obviously enough, should copy my input. And it does work, for basic ASCII text files.
However, if I send it a gif, in particular this one, but applicable to most (http://www.cs.utexas.edu/~peterson/prog2/smile.gif), then when I redir... |
getcharreturns anint, not achar. The distinction is important because it might returnEOFwhich is a value which cannot be a char.
You can't reliably test for EOF if you convert the return value ofgetcharto achar. The loop will terminate when you hit the character whose value is(char)EOF.
Fix it by declaringchas anint... |
This question already has answers here:What is a void pointer and what is a null pointer?(9 answers)Closed9 years ago.
So, I'm reading Beej's Guide to Network Programming, and he uses this function:
```
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa... |
The '*' means that the function is returning a void *. This is a pointer which can be cast to any other pointer.
|
I expected this program to stop the loop when i press enter button but instead the terminal become blank and do not show anything. Whats wrong with this?
```
#include <stdio.h>
int main()
{
int c;
printf("Enter a char(To exit loop press enter)");
for(c=' ';c!='\n';)
{
scanf("%d",&c);
putcha... |
So, see following fixes :-
```
char c ; // Use a char
char ch;
printf("Enter a char(To exit loop press enter)");
scanf("%c",&c);
for(;c!='\n';)
{
//Eat up the trailing newline from previous input
while(( ch =getchar() ) != '\n' && (ch != EOF ));
scanf("%c",&c);
pu... |
I am parsing a file with the following content:
```
0x1001
0x1001
0x0004
...
```
Here is part of my code:
```
while(fgets (line, sizeof(line),fp) != NULL)
{
inst[count] = atoi(line);
printf("%d\n",inst[count]);
count++;
}
```
Myprintf()result is then only zeroes. I would like to keep the exactly same values... |
You can't useatoi()to parse hexadecimal integers, it only handles decimal.
Usesscanf():
```
if(sscanf(line, "%x", &inst[count]) == 1)
printf("got 0x%x\n", inst[count]);
```
|
```
int number1 = 23;
int number2 = 100;
printf("Output: %.2d", double(number1) / number2);
```
This I want:
```
Output: 0.23
```
This I get:
```
error: expected expression before ‘double’
```
I don't understand the error message. How to do cast the integer to double and perform the calculation?
|
That's because you are typecasting the wrong way, also the format specifier is incorrect:
```
printf("Output: %.2f", (double)number1 / number2);
```
Here is the Output:
http://ideone.com/10a1Ka
|
I am parsing a file with the following content:
```
0x1001
0x1001
0x0004
...
```
Here is part of my code:
```
while(fgets (line, sizeof(line),fp) != NULL)
{
inst[count] = atoi(line);
printf("%d\n",inst[count]);
count++;
}
```
Myprintf()result is then only zeroes. I would like to keep the exactly same values... |
You can't useatoi()to parse hexadecimal integers, it only handles decimal.
Usesscanf():
```
if(sscanf(line, "%x", &inst[count]) == 1)
printf("got 0x%x\n", inst[count]);
```
|
```
int number1 = 23;
int number2 = 100;
printf("Output: %.2d", double(number1) / number2);
```
This I want:
```
Output: 0.23
```
This I get:
```
error: expected expression before ‘double’
```
I don't understand the error message. How to do cast the integer to double and perform the calculation?
|
That's because you are typecasting the wrong way, also the format specifier is incorrect:
```
printf("Output: %.2f", (double)number1 / number2);
```
Here is the Output:
http://ideone.com/10a1Ka
|
This question already has answers here:How do you determine the size of a file in C?(15 answers)Closed9 years ago.
My question is simple:
Should I use fseek with SEEK_END to get to the end of a file and then get the length of it ?
Because in the man it is said:
Library implementations are allowed to not meaningfull... |
Theftellfunction returns a long, which means that on an ILP32 system you can't correctly get the size of a file larger than 2GB. You should use thestatfunction or similar to get the size of a file; check the manual for the operating system you're targeting in case you have use a different function name (stat64) or def... |
I want to ask what does C do when it sees an index on a pointer to pointer; for example:
```
struct X {
int a;
int b;
};
struct X ** ptr;
```
What will happen if a statement contains :
```
ptr[i] // where i is an unsigned int
```
|
Any pointer can be used with array indexing, soptr[i]will be a pointer tostruct X.
However, you have to allocate memory forptrfirst of course, otherwise you will dereference an uninitialized pointer leading to undefined behavior. And if you dereferenceptr[i]without initializing that pointer, then you're again have un... |
Even after using pointers the numbers are not getting swapped in the main function. I know there is some reason but could not find what it is?
```
#include <stdio.h>
void swap(int*, int*);
int main()
{
int *ptr, *ptr2;
int num1 = 90;
int num2 = 900;
ptr = &num1;
ptr2 = &num2;
printf("Befo... |
You are swapping the pointers, not the pointed values. Change the swap function into:
```
void swap(int *ptr, int *ptr2)
{
int temp = *ptr;
*ptr = *ptr2;
*ptr2 = temp;
}
```
|
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
how do i cast the void pointer to char array in a multithreaded program in C
```
void* write(void* ptr) { ... |
You can't.
You can cast it to acharpointer, however:
```
void* write(void* ptr){
char *array;
array= (char*)ptr;
printf("%s",array);
}
```
|
I haveint x = 346.
I need to get in turn, each time a new digit of it, so first 3, then 4, then 6.
Usingfloordoes not help me here,
and other examples here give only the left/right digit.
Is there a simple algorithm?
|
a%10gives you the last digit of a number i.e. its remainder when divided by 10. You can print all the digits of a number like so:
```
void print_digits(int a) {
while (a > 0) {
printf("%d\n", a%10);
a /= 10;
}
}
```
This will print the digits from least significant to most significant. You can get them i... |
I know that in Solaris 10 Sun now Oracle don't provide static version of C library i.e libC.a
but I check that same thing is not possible using Sun Studio either, I was under impression that C library are provided by Compiler just like Visual Studio provides C runtime libraries.
So is on Solaris C libray is provide... |
Not sure you can find one. This is "by design" - while the stdlib API are stable, the internals change between releases of the OS, so they force everyone to link dynamically to avoid breakages.
Using dynamic versionin theorykeeps your executables portable across different Solaris releases (but it is not guaranteed).
... |
I have the following code for printing a UUID which works fine:
```
void puid(uuid_t u)
{
int i;
printf("%8.8x-%4.4x-%4.4x-%2.2x%2.2x-", u.time_low, u.time_mid,
u.time_hi_and_version, u.clock_seq_hi_and_reserved,
u.clock_seq_low);
for (i = 0; i < 6; i++)
printf("%2.2x", u.node[i]);
pr... |
what about :
```
char uuid[40];
sprintf(uuid, "%8.8x-%4.4x-%4.4x-%2.2x%2.2x-%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x",
u.time_low, u.time_mid, u.time_hi_and_version, u.clock_seq_hi_and_reserved,
u.clock_seq_low, u.node[0], u.node[1], u.node[2], u.node[3], u.node[4], u.node[5]);
printf("%s\n", uuid);
```
|
I am using MinGW under a 64-Bit Windows 7. To compile my simple application I use the call:
gcc -o main.exe main.c
Then I get an Error that mylibmpc-3.dllis missing. I already set my PATH variable to thebindir of MinGW (there are only alibmpc-2.dlland alibmpc-10.dll.)
Can anyone help?
|
Seems that the correct way to solve this and make MinGW install the right version of the library is using themingw-gettool by calling it likemingw-get install mpc.
If anyone else is missing libmpc-3.dll for non MinGW related situations, seems that Cygwin has a package withlibmpc-3(http://www-uxsup.csx.cam.ac.uk/pub/w... |
```
#include <stdio.h>
#include <string.h>
int main()
{
char name[32][32];
char input[32];
int number;
int i;
for(i=0;i<10;i++)
{
fgets(input,sizeof(input),stdin);
sscanf(input,%s,name[i]);
}
//assume that we don't know variable name have 10 element of arrays.
//function to count how many elements of arr... |
How about initialising your target strings to 0 then checking if they are not null whilst printing?
```
#include <stdio.h>
#include <string.h>
int main()
{
char name[32][32] = {0};
...
for(i=0;i<32;i++)
{
if(name[i][0]!='\0')
printf("%s",name[i]);
}
}
```
|
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
How does otool and similar tools read load commands? I could not find any open source too... |
I would expect that the otool command would open the file and parse the header of the binary according to theOSX ABI Mach-O File Format
|
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
Why does the following code only work on the first iteration around the for loop?
```
typedef struct {
... |
It's because you only initialized thegoldmember of thefirstelement of the array. All the rest are uninitialized and have undefined values. Changing an undefined value is undefined behavior.
|
I 'm using C language to create a connection from client to server. I use a command:
```
iResult = connect(ServerSocket,(LPSOCKADDR)&addr, nSize);
```
In most of cases, when an server IP (in "addr") is recognized or in local network, it returns the result (fail or Ok) immediately, but if it is an IP out side of loca... |
You can find an example in this article:
How to set a socket connection timeout
Basically you have to use non-blocking socket I/O and use some form of I/O multiplexing (like select or poll).
|
I have the following code for printing a UUID which works fine:
```
void puid(uuid_t u)
{
int i;
printf("%8.8x-%4.4x-%4.4x-%2.2x%2.2x-", u.time_low, u.time_mid,
u.time_hi_and_version, u.clock_seq_hi_and_reserved,
u.clock_seq_low);
for (i = 0; i < 6; i++)
printf("%2.2x", u.node[i]);
pr... |
what about :
```
char uuid[40];
sprintf(uuid, "%8.8x-%4.4x-%4.4x-%2.2x%2.2x-%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x",
u.time_low, u.time_mid, u.time_hi_and_version, u.clock_seq_hi_and_reserved,
u.clock_seq_low, u.node[0], u.node[1], u.node[2], u.node[3], u.node[4], u.node[5]);
printf("%s\n", uuid);
```
|
I am using MinGW under a 64-Bit Windows 7. To compile my simple application I use the call:
gcc -o main.exe main.c
Then I get an Error that mylibmpc-3.dllis missing. I already set my PATH variable to thebindir of MinGW (there are only alibmpc-2.dlland alibmpc-10.dll.)
Can anyone help?
|
Seems that the correct way to solve this and make MinGW install the right version of the library is using themingw-gettool by calling it likemingw-get install mpc.
If anyone else is missing libmpc-3.dll for non MinGW related situations, seems that Cygwin has a package withlibmpc-3(http://www-uxsup.csx.cam.ac.uk/pub/w... |
```
#include <stdio.h>
#include <string.h>
int main()
{
char name[32][32];
char input[32];
int number;
int i;
for(i=0;i<10;i++)
{
fgets(input,sizeof(input),stdin);
sscanf(input,%s,name[i]);
}
//assume that we don't know variable name have 10 element of arrays.
//function to count how many elements of arr... |
How about initialising your target strings to 0 then checking if they are not null whilst printing?
```
#include <stdio.h>
#include <string.h>
int main()
{
char name[32][32] = {0};
...
for(i=0;i<32;i++)
{
if(name[i][0]!='\0')
printf("%s",name[i]);
}
}
```
|
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
How does otool and similar tools read load commands? I could not find any open source too... |
I would expect that the otool command would open the file and parse the header of the binary according to theOSX ABI Mach-O File Format
|
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
Why does the following code only work on the first iteration around the for loop?
```
typedef struct {
... |
It's because you only initialized thegoldmember of thefirstelement of the array. All the rest are uninitialized and have undefined values. Changing an undefined value is undefined behavior.
|
I 'm using C language to create a connection from client to server. I use a command:
```
iResult = connect(ServerSocket,(LPSOCKADDR)&addr, nSize);
```
In most of cases, when an server IP (in "addr") is recognized or in local network, it returns the result (fail or Ok) immediately, but if it is an IP out side of loca... |
You can find an example in this article:
How to set a socket connection timeout
Basically you have to use non-blocking socket I/O and use some form of I/O multiplexing (like select or poll).
|
If I write a message to a closed pipe then my program crash
```
if (write(pipe, msg, strlen(msg)) == -1) {
printf("Error occured when trying to write to the pipe\n");
}
```
how to check ifpipeis still opened before I writing to it?
|
The correct way is to test the return code ofwriteand then also checkerrno:
```
if (write(pipe, msg, strlen(msg)) == -1) {
if (errno == EPIPE) {
/* Closed pipe. */
}
}
```
But wait: writing to a closed pipe no only returns -1 witherrno=EPIPE, it also sends aSIGPIPEsignal which terminates your process... |
Is stdin is a pointer, as I have seen its usage in fgets().
I used '0' as we use for read or write mistakenly for stdin and got a segfault during fgets.
Is STDIN macro and 0 are the same.
Is stdin is a file pointer. Please explain about this
|
stdin is aFILE *fromstdio.h
```
STDIN_FILENO == fileno(stdin)
```
STDIN_FILENOis inunistd.hand is used for functions likewrite, whereas stdin as a File * is used for stdio functions likeprintf
|
I am currently working on the mergesort algorithm. I have three functions. list_sort_merge, mergelist and splitlist. list_sort_merge calls the other two to split and merge the list. I am having trouble getting this to work correctly.
So what happens when I run GDB is that I get through the split function and get each... |
Here is an explanation:http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
and the example code:http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.c
|
Using the OrientDB library by tglman and trying to run the sample code @https://github.com/tglman/orientdb-c/wiki/Start
https://github.com/tglman/orientdb-c
I can connect to the DB and set + retrieve a value in orientDB successfully -
However when I run a query usingo_database_document_query, it does not finish exe... |
I also debuged and found the same problem ... fixed and pushed on github!
|
I have two 2 dimensional arrays:
```
#define MAXSIZE 10
/* ... */
int A[MAXSIZE][MAXSIZE], B[MAXSIZE][MAXSIZE];
```
I'm reading in values from a file:
```
1 1 2
2 2 -6 4 5 6
```
On each line, the first two numbers are the row and column sizes for the array, after which are enough (arbitrary) values to fill up an a... |
Why don't you store the row/column sizes for each line into their variables?
```
int Arow, Acol, Brow, Bcol;
```
Normally, this would work:
```
int Acol = sizeof(A[0]);
int Arow = sizeof(A) / Acol;
```
But your arrays are initialized to fixed sizes.
Have you thought about usingmallocto dynamically allocatedAandB?... |
Is there a way to write a C preprocessor macro that expands to different things depending on what argument it receives?
```
#define foo() ???
/* 1 */
foo(name)
/* 2 */
foo(_)
```
Desired result:
```
/* 1 */
int name;
/* 2 */
/*ignore*/
```
Yes, I know macros are evil. I'm asking this mostly out of curiosity.
|
To expand on Gavin Smith's answer, you actually can check conditions within a macro expansion:
```
#define FOO_name 1
#define FOO__ 0
#define CONC(a,b) a##_##b
#define IF(c, t, e) CONC(IF, c)(t, e)
#define IF_0(t, e) e
#define IF_1(t, e) t
#define FOO(x) IF(CONC(FOO,x), int x;, )
FOO(name) // -> int name;
FOO(_) ... |
This question already has answers here:What is the best way to add two numbers without using the + operator?(26 answers)Closed9 years ago.
I am 9 grade, My math teacher asked me to add numbers with out using+sign in C program.
I trieda - (-b) = a + b;but my math teacher want some other option.
|
Use this function in your c program
```
int Add(int a, int b)
{
while (b)
{
// carry now contains common set bits of "a" and "b"
int carry = a & b;
// Sum of bits of "a" and "b" where at least one of the bits is not set
a = a ^ b;
// Carry is shifted by one so that ad... |
```
#include <stdio.h>
#include<stdlib.h>
int main(void){
int n1,k1;
int tot;
scanf("%d",k1);
scanf("%d",n1);
tot=((k1=1)?((n1(n1+1))/2):((n1(n1+1))/2)-((k1(k1+1))/2));
return 0;
}
```
this code is wrong?
Compiling it with Dev c++, gives me the error"called object is not a function"refered at
```
t... |
First of all you should pass the pointers to variables to thescanffunctions using&operator:
```
scanf("%d",&k1);
scanf("%d",&n1);
```
Secondly, you should correct mistakes in the syntax of your expression:
use==instead of=to check equalityexplicitly use*operator if you want to perform the multiclication.
tot=((k1=... |
This question already has answers here:Print part of a string in C(4 answers)Closed9 years ago.
Is it possible inCto set a number of chars to be output from string?
```
char const *str = "abcdefgh";
printf("%???s", str);
```
What should be placed instead of ??? to outputabc?
|
Yes, you could use a precision specifier, which would look something like this
```
printf("%.3s", str); // this prints "abc"
```
|
I am trying to compile a C file I have written that has the include#include <openssl/evp.h>on Solaris 10. The system OpenSSL files (including evp.h) are located under/usr/local/ssl/include/openssl, but I can't get them picked up running the following command:
```
gcc -O2 -fPIC -shared -static-libgcc -I$JAVA_HOME/inc... |
I've never seen $JAVA_HOME explicitly put in a gcc command before. What is the value of $JAVA_HOME supposed to be?
Can you try adding the necessary path directly to the gcc command? Just add
-I/usr/local/ssl/include
|
```
#include <stdio.h>
int main(void){
char a;
scanf("%s", &a);
return 0;
}
```
Works for me, but I wonder if in other context there might be any unexpected results.
|
Take this code for example -
```
#include <stdio.h>
int main(void){
char a;
char b = '1';
char c = '1';
scanf("%s", &a);
printf("%c = %c\n", b, c);
return 0;
}
```
You would expect it to print1 = 1, but just now when I ran it, it printed= 1(at least in my compiler, don't expect anything st... |
How can I make a pointer point to the last byte of
the physical memory and access its data?
Is this even possible?
|
No, since the language C does not specify the underlying memory architecture.
On select OS/architecture you may in an OS dependent or creative fashion.
|
InC99,6.5.3 Unary operators:
```
Syntax
1 unary-expression:
postfix-expression
++ unary-expression
-- unary-expression
unary-operator cast-expression
sizeof unary-expression
sizeof ( type-name )
unary-operator: one of
& * + - ~ !
```
This says that unary-operator is one of&,*,+,-,~,!, so I think that++,--andsizeofar... |
Linguistically the phraseunary-operator: one of & * + - ~ !means that they are unary operators, but not necessarily the only unary operators. If the phrase is instead interpreted mathematically one might think they are the only unary operators.
The title of the chapter is "Unary Operators" which indicates that the fi... |
Im trying to send something to the child after fork() i've set up dup2 to redirect the out puts for the child. but it looks like it's not getting the stream.
further more how do i get the out put from the child.
The file is an external executable that simply prints text but it's not showing.
Any help please?
|
You are usingpipeincorrectly, because it only needs to be called once (RTM).You're callingcallocincorrectly. Usecalloc (100, sizeof (char))Don't assign a constant string to a section of dynamically allocated memory. Usechar message[] = "sent from parent"instead. This way is also beneficial because you can usesizeofinw... |
Motivation:
I want to enable the memory detection of VC++, which requires that some statements must be at the forefront as follows:
```
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
```
Question:
Suppose I have a header fileforefront.h, what I want is the following effect:
a.cpp
```
#include ... |
Create your own header file with the following contents:
```
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
```
Now use the Forced Includes setting in the Advanced section of the project's settings. Any file specified there will be included before all others, in the order specified.
|
I am trying to run this code where i use short int.
```
int main() {
short int i=0;
while(++i)
printf("%u\n", i);
}
```
Ouput (using short int):
```
1
2
3...
32767
4294934528
.
.
4294967295(last value)
```
why is there sudden jump in value after 32767 any explanations??
I am using linu... |
Signed integer overflow is undefined behavior. Your program pushesibeyond the bounds of what can be stored in ashort, so the program is free to do absolutely anything.
|
Im using C to solve a coupled ODE system of 12 equations (I need to use C for external reasons). Im exporting the data to a .dat file using fprintf but now I need to solve this system for different values of my parameters and i dont want to create different files manually.
Does anyone knows how can I create different ... |
Just use a loop:
```
FILE *files[numfiles];
for (int i = 0; i < numfiles; i++)
{
char filename[20];
sprintf(filename, "results%d.dat", i);
files[i] = fopen(filename, "w");
}
```
|
```
#include <stdio.h>
int main(void){
char a;
scanf("%s", &a);
return 0;
}
```
Works for me, but I wonder if in other context there might be any unexpected results.
|
Take this code for example -
```
#include <stdio.h>
int main(void){
char a;
char b = '1';
char c = '1';
scanf("%s", &a);
printf("%c = %c\n", b, c);
return 0;
}
```
You would expect it to print1 = 1, but just now when I ran it, it printed= 1(at least in my compiler, don't expect anything st... |
How can I make a pointer point to the last byte of
the physical memory and access its data?
Is this even possible?
|
No, since the language C does not specify the underlying memory architecture.
On select OS/architecture you may in an OS dependent or creative fashion.
|
InC99,6.5.3 Unary operators:
```
Syntax
1 unary-expression:
postfix-expression
++ unary-expression
-- unary-expression
unary-operator cast-expression
sizeof unary-expression
sizeof ( type-name )
unary-operator: one of
& * + - ~ !
```
This says that unary-operator is one of&,*,+,-,~,!, so I think that++,--andsizeofar... |
Linguistically the phraseunary-operator: one of & * + - ~ !means that they are unary operators, but not necessarily the only unary operators. If the phrase is instead interpreted mathematically one might think they are the only unary operators.
The title of the chapter is "Unary Operators" which indicates that the fi... |
Im trying to send something to the child after fork() i've set up dup2 to redirect the out puts for the child. but it looks like it's not getting the stream.
further more how do i get the out put from the child.
The file is an external executable that simply prints text but it's not showing.
Any help please?
|
You are usingpipeincorrectly, because it only needs to be called once (RTM).You're callingcallocincorrectly. Usecalloc (100, sizeof (char))Don't assign a constant string to a section of dynamically allocated memory. Usechar message[] = "sent from parent"instead. This way is also beneficial because you can usesizeofinw... |
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
How can I use a char to get the status of a bit, Later I need to increment the char variable to 1
```
char... |
In an optimized build, the compiler may replace that by
```
char CValue = (dataPresent & BINARYDATA_MASK)? 2: 1;
```
Because there's only one line in the optimized code, you won't see the debugger stop multiple times while single-stepping.
|
I'm using cluster resources from my academic provider (PDC, Sweden) that uses theMIT-Kerberos authentication protocolfor the users to sign in securely.
I'm also usingNetbeansto develop C and Fortran code. Netbeans has a feature that lets you build your code on a remote host while you are working on your localhost/Des... |
Eclipse with thePhotran pluginare commonly mentioned. I never used it myself, but Eclipse should alsosupport authentication via Kerberos.
Seeherefor more on Eclipse and SSH.
|
I have the following code in C. I run it at FreeBSD. I compile it ascc -o bbb bb.c. Then run and get the output
```
$ ./bbb
-1
stat: No such file or directory
```
This is the Code:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include... |
int stat(const char *restrict path, struct stat *restrict buf);
Thestat()function shall obtain information about the named file and write it to the area pointed to by the buf argument. The path argument points to a pathname naming a file.
In your codestat("/", st);is path for directory only.
|
Is there a way to put an array inside another array without using loops? This loop feels a bit weird:
```
uint8_t buf0[50];
populate_buf( buf0 );
uint8_t buf1[100];
buf1[0] = 'S';
for ( uint8_t i = 0; i < 50; i++ )
buf1[1+i] = buf0[i];
```
|
```
memcpy(&buf1[1], &buf0[0], sizeof buf0);
```
|
I am trying to use bitwise operators on uint64_t type. When I run this, I get output of 37 (47 - 10) bits even though it needs to be 54 bits (64-10 bits) long. How can I fix this?
```
uint64_t temp = addr; //(addr input - 11111111110100011010111011011111000101111001000)
temp = temp >> 10;
return temp; //returns 37 ... |
tempis 64 bits because that's how you declared it.
When you print it, the initial zeroes don't show unless you specify that you want them to show in your print statement.
Try withaddr = 1000000000100000000010000000001000000000100000000010000000001000(or any other 64 bit number starting with a1) and you will see.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ... |
The only way to access the system memory is from a kernel mode driver. So, if you are going to do this, you'll have to write such a thing.
|
This question already has answers here:Values obtained in case of a recursive function(3 answers)Closed9 years ago.
Shouldn't this program run infinitely because main is being called every time? And why it's output is0 0 0 0? I know it's a noob question but I am not able to get it. What--ido and what is the effect of... |
Thestatic intis not reinitialized each time. Thus, each time main() is called, i is one lower.when(--i)is zero, the recursive loop terminates.
Thus, it starts off withi=5, and calls a new copy. This one hasi=4, which again calls a new copy. This continues untili=0, at which point the function just terminates. Con... |
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
Is it possible to pass a pointer to an array from my app to a console exe program?
The scenario is: my app... |
To exchange data between separate processes, you need a means of inter-process communication.
Options include:
shared memorypipespossibly even sockets
Which of the above is appropriate for you depends on the type and amount of data you want to exchange, how frequently you want to exchange it, etc.
|
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
How can I use a char to get the status of a bit, Later I need to increment the char variable to 1
```
char... |
In an optimized build, the compiler may replace that by
```
char CValue = (dataPresent & BINARYDATA_MASK)? 2: 1;
```
Because there's only one line in the optimized code, you won't see the debugger stop multiple times while single-stepping.
|
I'm using cluster resources from my academic provider (PDC, Sweden) that uses theMIT-Kerberos authentication protocolfor the users to sign in securely.
I'm also usingNetbeansto develop C and Fortran code. Netbeans has a feature that lets you build your code on a remote host while you are working on your localhost/Des... |
Eclipse with thePhotran pluginare commonly mentioned. I never used it myself, but Eclipse should alsosupport authentication via Kerberos.
Seeherefor more on Eclipse and SSH.
|
I have the following code in C. I run it at FreeBSD. I compile it ascc -o bbb bb.c. Then run and get the output
```
$ ./bbb
-1
stat: No such file or directory
```
This is the Code:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include... |
int stat(const char *restrict path, struct stat *restrict buf);
Thestat()function shall obtain information about the named file and write it to the area pointed to by the buf argument. The path argument points to a pathname naming a file.
In your codestat("/", st);is path for directory only.
|
Is there a way to put an array inside another array without using loops? This loop feels a bit weird:
```
uint8_t buf0[50];
populate_buf( buf0 );
uint8_t buf1[100];
buf1[0] = 'S';
for ( uint8_t i = 0; i < 50; i++ )
buf1[1+i] = buf0[i];
```
|
```
memcpy(&buf1[1], &buf0[0], sizeof buf0);
```
|
I have a character obtained from fgetc(file) stored in the variable i. I want to compare the character contained within i to a constant, i.e.(i == "\n"), but of course i is of the integer type. I tried((char)i == "\n")but it doesn't work. In both cases I get "warning: comparison between pointer and integer", but I'm n... |
The problem here actually derived from the use of double quotation marks as opposed to single quotation marks (the question now has double quotation marks in place of singles to reflect the original code. When replaced with singles, it worked.
|
I would like to dynamically allocate memory for an input string whose size is unknown at the time of input,with exact precision, i.e.
if the string is "stack" I would like to allocate 6 bytes only.
I guess the only way is to keep on increasing the upper limit of the array depending on the input but I am unable to fig... |
strdup()is your friend.
```
char *p = strdup("stack");
```
|
I got some problem with RVCT compile environment, need your help.
There is a function like this
```
int lib_func(int b)
```
but i don't have the source code of this function.
I want to wrap this function and add some debug flag.
In GCC, i can create__wrap_lib_func, and call__real_lib_func,
then modify the makefi... |
There is the $Super$$/$Sub$$ functionality in the linker, that lets you "intercept" calls:http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0474i/Chdefdce.html
Of course that document is for version 5.03, but the functionality was there in 3.1 and I would be surprised if the syntax has changed.
|
This typedef works:
```
typedef void (*mem_deallocator)(void*);
```
However this one
```
typedef void* (*mem_allocator)(size_t);
```
gives the warning:
warning: parameter names (without types) in function declaration [enabled by default]
I'm using GCC 4.8.1 and I'm compiling with-c -Wall.
How to fix the code so... |
size_tis defined in the following headers, you need to include at least one of them.
```
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <wchar.h> //since C99
#include <uchar.h> //since C11
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.