question
stringlengths 25
894
| answer
stringlengths 4
863
|
|---|---|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago.
In C, why does
strtoul(argv[1])
just doesn't work? It looks like more parameters are needed but I can't prevent how long the number will be.
Thanks!
p.s. (argv[1] is properly setted).
|
Because you're calling it with the wrong number of arguments. Try
```
strtoul(argv[1], 0, 0);
```
Or if you want to enforce base-10 only:
```
strtoul(argv[1], 0, 10);
```
Be sure you included<stdlib.h>too!
|
I installed the gmp libraries in cygwin via its installer. I tried to compile a simple program with gcc.
```
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
int
main(void)
{
mpz_t test;
int i;
printf("enter number\n");
gmp_scanf("%Z",&test);
gmp_printf("test=%Z",test);
i=mpz_probab_prime_p(test,5);
if(i)
printf("prime\n");
else
printf("not prime\n");
return 0;
}
```
But I got this:
```
/cygdrive/c/Users/xxxxx/Documents/NetBeansProjects/rsa_system/main.c:13: undefined reference to `__imp____gmp_scanf'
```
This is the first time that I try to use a non-standard library and I'm getting confused here. My compiler is set to Cygwin and I've done all the installation part. Any ideas on what may be wrong? Thank you.
|
Are you asking gcc to link GMP?
i.e.:gcc -lgmp main.c ....
|
why should a code like this should provide a so high result when I give it the number 4293974227 (or higher)
```
int main (int argc, char *argv[])
{
unsigned long long int i;
unsigned long long int z = atoi(argv[1]);
unsigned long long int tmp1 = z;
unsigned long long int *numbers = malloc (sizeof (unsigned long long int) * 1000);
for (i=0; tmp1<=tmp1+1000; i++, tmp1++) {
numbers[i] = tmp1;
printf("\n%llu - %llu", numbers[i], tmp1);
}
}
```
Result should start with the provided number but starts like this:
```
18446744073708558547 - 18446744073708558547
18446744073708558548 - 18446744073708558548
18446744073708558549 - 18446744073708558549
18446744073708558550 - 18446744073708558550
18446744073708558551 - 18446744073708558551
```
ecc...
What's this crap??
Thanks!
|
atoi()returnsint. If you need larger numbers, trystrtol(),strtoll(), or their relatives.
|
Why does
```
char line[10] = "1234";
```
work fine but
```
char line[10];
line = "1234";
```
throws an
```
error: incompatible types in assignment
```
error?
|
Arrays are not pointers. In your second example,lineis a non-modifiable lvalue, but more importantly, no matter what you put on the righthand side, it can't have typechar [10](because arrays decay to pointers in non-lvalue context) and thus the types can never match.
For what it's worth, a string literal has typechar [N], notconst char [N]and especially notconst char *, despite the fact that attempts to modify it invoke undefined behavior. (HereNis the length of the quoted text in bytes, including the added null terminator.)
|
I am trying to build my first Windows TUI Console app and i am facing some problems...Scanf nor fgets prevents user from entering unlimted characters unless hits enter etc..In a TUI interface thats a problem.. because it can get overwrite the line below...Is there any solution for this apart from getch
|
No, there isn't, at least not portably. C input is stream based, and doesn't have a concept of a keyboard. If you really want to write a text user interface, usencursesorpdcurses.
|
InCProgramming, We can enable/disable loop optimization using#pragmapreprocessor directive.
In which scenario,loop optimizationshould turned off ?
|
Optimisation is off by default when you compile for debug (so that source code lines in the debugger exactly match the code being executed).
You would only use the pragma in very specific circumstances, such as:
You find an optimisation limitation/bug leading to undefined behaviour (What Every C Programmer Should Know About Undefined Behavior(Thanks to @R)You need exact real-time timing
|
I have to write a simple program to output 16 bytes of data to a file at 0 and 48th position and have come up with this program:
```
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int f = create("test.tmp",774);
if(f>0)
{
write(f,"DEPARTMENT OF CS",16);
lseek(f,48,SEEK_SET);
write(f,"DEPARTMENT OF IS",16);
}
return 0;
}
```
What is wrong with this? It tells me when I compile usingcc 7a.sh -llthat:
undefined to reference to 'create'
|
There's no function namedcreate
It's namedcreat
|
How can I update a GTK+ interface on a periodic event. For example, let's say I wanted to update a text field containing the time every 200 milliseconds. How is this typically done?
Update:
Another question (How one executes a periodic job in gtk application?) mentiones g_timeout_add. Is this the best way to go about doing this? It is said in that thread that it may not be efficient?
|
This tutorialhas an example. (Search for the section titled "A timer example".)
The short answer is "useg_timeout_add".
|
I want to check whether an allocated memory is aligned or not. I am using_aligned_malloc(size, align);And it returns a pointer. Can I check it by simply dividing the pointer content by 16 for example? If the the pointer content is divisible by 16, does it mean that the memory is aligned by 16 bytes?
|
An "aligned" pointer by definition means that the numeric value of the pointer is evenly divisible by N (where N is the desired alignment). To check this, cast the pointer to an integer of suitable size, take the modulus N, and check whether the result is zero. In code:
```
bool is_aligned(void *p, int N)
{
return (int)p % N == 0;
}
```
If you want to check the pointer value by hand, just look at the hex representation of the pointer and see whether it ends with the required number of 0 bits. A 16 byte aligned pointer value will always end in four zero bits, for example.
|
Can we say that "C language operators are polymorphic" ?
For example if
```
int a, b;
float p, q;
a+b;
a+p;
p+q;
```
etc will generate different code when assembled, as the type conversion is needed the floating point coprocessor instruction needs to be executed to make the conversion and the floating point additions. So the operators operate differently depending on the objects they act upon.
Although these are implicit so if this can theoretically be called static polymorphism, operator overloading?
|
Yes, in theory this could be called static polymorphism or operator overloading. But since the polymorphism is fixed in its range of applicable types by the language definition, it's not a very interesting polymorphism.
|
I use ANSI C89 (not C++), and I want to generateNaN,-Infinityand+Infinity.
Is there any standard way (eg. standard macro)?
Or is there any platform and compiler independent way to generate these numbers?
```
float f = 0.0 / 0.0; // Is f ALWAYS in any platform is NaN?
```
|
There is in C99, but not in previous standards AFAIK.
In C99, you'll haveNANandINFINITYmacros.
From"Mathematics<math.h>"(§7.12) section
The macroINFINITYexpands to a constant expression of type float representing positive or unsigned infinity, if available; ...
If you're stuck with ANSI C89, you're out of luck. SeeC-FAQ 14.9.
|
The code:
```
int main(void)
{
printf("pid: %d\n", getpid());
pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork Failed!");
exit(-1);
} else if (pid == 0) {
execv("sum", argv);
} else {
printf(" pid: %d\n", pid);
wait(NULL);
}
}
```
The output:
```
pid: 280
pid: 281
```
The question:
Why are the two pid's different. I thought they should be the same because the parent is what is executing in theelseblock and the parent is what is executing before the fork so they should be the same, no?
|
```
RETURN VALUE
On success, the PID of the child process is returned in the parent,
and 0 is returned in the child. On failure, -1 is returned in the parent,
no child process is created, and errno is set appropriately.
```
So, in the parent process, fork() returns the pid of the child process that was created.
|
I have been using the GCC Compiler for months, which is great, and works very well. But I wonder which C++ Compiler do big/medium enterprises use for high optimizations/performance in Linux (x86, PowerPC...).
It may seem a very stupid question, but I havent found the answer anywhere.
As far as I know, the best PowerPC Compiler is the XL, but x86 I dont know anything.
EDIT: Thanks a lot for all the answers. They were all very helpful. You have convinced me to use GCC ;) Regards!
|
In the places I have worked we have always used gcc, even for embedded applications/software.
Performance improvements are much more likely to come from your code rather than your compiler choice anyway!
|
I want to convert an 32-bit ASCII number (e.g. "FE257469") to the equivalent 32-bit hex number which will be stored on a 32-bit variable. Most importnatly, I want to do thatwithoutusing any library function like sscanf(), atoi(), etc.
Any ideas on that?
Thank in advance.
|
Here is an implementation of such a function based on a switch:
```
unsigned int parseHex( char *str )
{
unsigned int value = 0;
for(;; ++str ) switch( *str )
{
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
value = value << 4 | *str & 0xf;
break;
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
value = value << 4 | 9 + *str & 0xf;
break;
default:
return value;
}
}
```
|
I have this string
```
c1eb044f0708015b267913fc4dff5aabe3dd4a97f10f7ba935cd360000000000
```
How does one swap it so it becomes
```
000000000036cd35a97b0ff1974adde3ab5aff4dfc1379265b0108074f04ebc1
```
Those two are basically examples, but that is what i need to do, but not know how as i have very little knowledge of C.
The above two strings are actually unsigned char[] in the C program
P.S
Don't think i didn't go through google. I did, but i found very little of what i needed so every attempt to do that failed.
|
```
for (int i = 0; i < size; i += 2) {
myNewStr[size - i - 2] = myStr[i];
myNewStr[size - i - 1] = myStr[i + 1];
}
```
|
I have a question about program exit state in Linux. In my program, I fork a child process and invokewaitpidto reap it. Whenwaitpidreturns, I wanna check exit state of my child process. I turn to manual for help and find that the second argument ofwaitpidwill hold exit state and I can use macroWEXITSTATEto read it. However, this macro just extract least significant 8 bits of the real exit state, while in manual of functionexit(int ret_val), it will exit withret_val & 0x377, instead of least significant 8 bits.
My question is, where is the other more bits? Do we simply drop them? Why Linux employ this strategy? Doesn't this implementation introduce trouble to our program?
Thanks and Best Regards.
|
I think you will find that0x377is really, or should have been,0377.
It's octal, so3778is 8 bits.
|
Fromhttp://www.adp-gmbh.ch/cpp/gcc/create_lib.html:
Note: the library must start with the three lettersliband have the suffix.a.
Is this an operating system convention, or agcc/arquirk? Xcode seems to be able to create libraries without the prefix. What's it doing differently?
|
You can name a library whatever you want, but if you want gcc's-lflag to find the right one, you need to name it the way that link describes. For example:
```
gcc -o myapp myapp.c -lm
```
Will compilemyapp.c, link the resulting object withlibm.a, and output an executable calledmyapp. These days, there might be a more complicated search path involving dynamic library names, etc., but you should get the basic idea from this example.
From thegcc man page:
-llibrary...... surroundslibrarywithliband.aand searches several directories.
|
select(2) (amongst other things) tells me whether I can write to a fd of a file without blocking. However, does it guarentee me that I can write a full 4096 bytes without blocking?
NoteI am interested in normal files on disk. Not sockets or the like.
In other words: doesselectsignal when we can just write one single byte to a file fd without blocking,ordoes it signal when we can writen(4096, ... ?) bytes to a file fd without blocking.
|
Wheneverselect()indicates that your file is ready, you can try writing N bytes, for any N>0.write()will return the number of bytes actually written. If it equals N, you can write again. If it's less than N, then the next write will block.
NoteNormal files on disk don't block. Sockets, pipes and terminals do.
|
```
#include <stdio.h>
int main()
{
int i = 10;
printf("%d\n", ++(-i)); // <-- Error Here
}
```
What is wrong with++(-i)? Please clarify.
|
-igenerates a temporary and you can't apply++on a temporary(generated as a result of an rvalue expression). Pre increment++requires its operand to be an lvalue,-iisn't an lvalue so you get the error.
|
I was trying some C++, but I'm too new to this and you can say that this is my first day at C++. So I was trying to create a function but I was stuck with arrays! When I create a Character based array like this :
```
char x[7][7] = {"sec","min","hr","day","week","month","year"};
```
And when I try to fetch the data from it like this :
```
for (i=0;i<=7;i++){
cout << x[i] << "\n";
}
```
I get some strange results! Like this :
Can anyone tell me where I'm going totally wrong! And please I'm new to C++ so can you provide me a good explanation.
|
Since you have 7 values, and the array is indexed from 0, you only need to count up to 6, not 7. Modify yourforloop asfor (i=0;i < 7;i++). (<instead of<=.)
You're going over the end of the array, which may give you garbage data or may just crash your program.
|
In3["XoePhoenix"], array index is of type array of characters. Can we do this in C? Isn't it true that an array index must be an integer?
What does3["XeoPhoenix"]mean?
|
3["XoePhoenix"]is the same as"XoePhoenix"[3], so it will evaluate to the char'P'.
The array syntax in C is not more than a different way of writing*( x + y ), wherexandyare the sub expressions before and inside the brackets. Due to the commutativity of the addition these sub expressions can be exchanged without changing the meaning of the expression.
So3["XeoPhoenix"]is compiled as*( 3 + "XeoPhoenix" )where the string decays to a pointer and3is added to this pointer which in turn results in a pointer to the 4th char in the string. The*dereferences this pointer and so this expression evaluates to'P'.
"XeoPhoenix"[ 3 ]would be compiled as*( "XeoPhoenix" + 3 )and you can see that would lead to the same result.
|
i am creating file system filter driver and need to open some files to check attributes in dispatch routines. I am using ZwCreateFile(). But my dispatch routines is called at every file system request, so my ZwCreateFile() will then call again my dispatch routine. What is the best method to not enter deadlock? I think using flags or something is good choice?
I have tested and simple signing the flag in device extension still not changes the flag in some situations or the flag contain old data.
Thank you
|
TryIoCreateFileSpecifyDeviceObjectHint,IoCreateFileExorFtlCreateFile.
|
In static linking, how does the linker knows which library file to link the user's compiled object code against? I mean the header only contains the function protoytpes that may be used in the source code, not the library file name.. isn't it?
|
That's why you provide the linker with a list of libraries to link against!
e.g. for GCC, you might do something like:
```
gcc my_prog.o -lm -lpthread -o my_prog
```
Here, the-lflag is used to tell the linker to link againstlibmandlibpthread.
|
I'm writing code for a primality testing function that handles long long int's.Do I have to use special operators for such large numbers?Is there any documentation concerning large number manipulation in C?I'm using the gnu standard library.Thanks.
|
No, you don't need to do anything special. You handle along long intjust the same way as you would handle aint. Just beware of overflows, as with every native integer type.
|
I need to create several id's for several structs.
Now I want that each id will start from 00001 to 99999
for example:
the id of the first struct is 00001the id of the second struct is 00002...and so on...
Now I need toscanfit, and thenprintfit so the id that shown in the black window will look like this:The id of the first struct is: 00001
How do I do this?
Do I need to use regularintordouble?
And how do i use a loopfor (i=0 ; i<99999 ;i++)while i is the last digits?
Thank you a lot!
|
For a numerical variable, there is no concept of "leading zeroes". So if you want to use "0001" in your code, you will have to convert it into a string, adding leading 0's as required.
|
I have this string
```
c1eb044f0708015b267913fc4dff5aabe3dd4a97f10f7ba935cd360000000000
```
How does one swap it so it becomes
```
000000000036cd35a97b0ff1974adde3ab5aff4dfc1379265b0108074f04ebc1
```
Those two are basically examples, but that is what i need to do, but not know how as i have very little knowledge of C.
The above two strings are actually unsigned char[] in the C program
P.S
Don't think i didn't go through google. I did, but i found very little of what i needed so every attempt to do that failed.
|
```
for (int i = 0; i < size; i += 2) {
myNewStr[size - i - 2] = myStr[i];
myNewStr[size - i - 1] = myStr[i + 1];
}
```
|
I have a question about program exit state in Linux. In my program, I fork a child process and invokewaitpidto reap it. Whenwaitpidreturns, I wanna check exit state of my child process. I turn to manual for help and find that the second argument ofwaitpidwill hold exit state and I can use macroWEXITSTATEto read it. However, this macro just extract least significant 8 bits of the real exit state, while in manual of functionexit(int ret_val), it will exit withret_val & 0x377, instead of least significant 8 bits.
My question is, where is the other more bits? Do we simply drop them? Why Linux employ this strategy? Doesn't this implementation introduce trouble to our program?
Thanks and Best Regards.
|
I think you will find that0x377is really, or should have been,0377.
It's octal, so3778is 8 bits.
|
Fromhttp://www.adp-gmbh.ch/cpp/gcc/create_lib.html:
Note: the library must start with the three lettersliband have the suffix.a.
Is this an operating system convention, or agcc/arquirk? Xcode seems to be able to create libraries without the prefix. What's it doing differently?
|
You can name a library whatever you want, but if you want gcc's-lflag to find the right one, you need to name it the way that link describes. For example:
```
gcc -o myapp myapp.c -lm
```
Will compilemyapp.c, link the resulting object withlibm.a, and output an executable calledmyapp. These days, there might be a more complicated search path involving dynamic library names, etc., but you should get the basic idea from this example.
From thegcc man page:
-llibrary...... surroundslibrarywithliband.aand searches several directories.
|
select(2) (amongst other things) tells me whether I can write to a fd of a file without blocking. However, does it guarentee me that I can write a full 4096 bytes without blocking?
NoteI am interested in normal files on disk. Not sockets or the like.
In other words: doesselectsignal when we can just write one single byte to a file fd without blocking,ordoes it signal when we can writen(4096, ... ?) bytes to a file fd without blocking.
|
Wheneverselect()indicates that your file is ready, you can try writing N bytes, for any N>0.write()will return the number of bytes actually written. If it equals N, you can write again. If it's less than N, then the next write will block.
NoteNormal files on disk don't block. Sockets, pipes and terminals do.
|
```
#include <stdio.h>
int main()
{
int i = 10;
printf("%d\n", ++(-i)); // <-- Error Here
}
```
What is wrong with++(-i)? Please clarify.
|
-igenerates a temporary and you can't apply++on a temporary(generated as a result of an rvalue expression). Pre increment++requires its operand to be an lvalue,-iisn't an lvalue so you get the error.
|
I was trying some C++, but I'm too new to this and you can say that this is my first day at C++. So I was trying to create a function but I was stuck with arrays! When I create a Character based array like this :
```
char x[7][7] = {"sec","min","hr","day","week","month","year"};
```
And when I try to fetch the data from it like this :
```
for (i=0;i<=7;i++){
cout << x[i] << "\n";
}
```
I get some strange results! Like this :
Can anyone tell me where I'm going totally wrong! And please I'm new to C++ so can you provide me a good explanation.
|
Since you have 7 values, and the array is indexed from 0, you only need to count up to 6, not 7. Modify yourforloop asfor (i=0;i < 7;i++). (<instead of<=.)
You're going over the end of the array, which may give you garbage data or may just crash your program.
|
In3["XoePhoenix"], array index is of type array of characters. Can we do this in C? Isn't it true that an array index must be an integer?
What does3["XeoPhoenix"]mean?
|
3["XoePhoenix"]is the same as"XoePhoenix"[3], so it will evaluate to the char'P'.
The array syntax in C is not more than a different way of writing*( x + y ), wherexandyare the sub expressions before and inside the brackets. Due to the commutativity of the addition these sub expressions can be exchanged without changing the meaning of the expression.
So3["XeoPhoenix"]is compiled as*( 3 + "XeoPhoenix" )where the string decays to a pointer and3is added to this pointer which in turn results in a pointer to the 4th char in the string. The*dereferences this pointer and so this expression evaluates to'P'.
"XeoPhoenix"[ 3 ]would be compiled as*( "XeoPhoenix" + 3 )and you can see that would lead to the same result.
|
i am creating file system filter driver and need to open some files to check attributes in dispatch routines. I am using ZwCreateFile(). But my dispatch routines is called at every file system request, so my ZwCreateFile() will then call again my dispatch routine. What is the best method to not enter deadlock? I think using flags or something is good choice?
I have tested and simple signing the flag in device extension still not changes the flag in some situations or the flag contain old data.
Thank you
|
TryIoCreateFileSpecifyDeviceObjectHint,IoCreateFileExorFtlCreateFile.
|
In static linking, how does the linker knows which library file to link the user's compiled object code against? I mean the header only contains the function protoytpes that may be used in the source code, not the library file name.. isn't it?
|
That's why you provide the linker with a list of libraries to link against!
e.g. for GCC, you might do something like:
```
gcc my_prog.o -lm -lpthread -o my_prog
```
Here, the-lflag is used to tell the linker to link againstlibmandlibpthread.
|
I'm writing code for a primality testing function that handles long long int's.Do I have to use special operators for such large numbers?Is there any documentation concerning large number manipulation in C?I'm using the gnu standard library.Thanks.
|
No, you don't need to do anything special. You handle along long intjust the same way as you would handle aint. Just beware of overflows, as with every native integer type.
|
I need to create several id's for several structs.
Now I want that each id will start from 00001 to 99999
for example:
the id of the first struct is 00001the id of the second struct is 00002...and so on...
Now I need toscanfit, and thenprintfit so the id that shown in the black window will look like this:The id of the first struct is: 00001
How do I do this?
Do I need to use regularintordouble?
And how do i use a loopfor (i=0 ; i<99999 ;i++)while i is the last digits?
Thank you a lot!
|
For a numerical variable, there is no concept of "leading zeroes". So if you want to use "0001" in your code, you will have to convert it into a string, adding leading 0's as required.
|
What would be the output of this program ?
```
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int x=20,y=30,z=10;
int i=x<y<z;
printf("%d",i);
getch();
}
```
Actuallyi=20<30<10, so the condition is false and the value ofishould be 0 butiequals 1. Why?
|
Thisint i=x<y<z;doesn't work the way you intended.
The effect isint i=(x<y)<z;, wherex<yis evaluated first, and the valuetrueis then compared toz.
Pascal points out below that in C the result of the comparison is1instead oftrue. However, the C++trueis implicitly converted to1in the next comparison, so the result is the same.
|
I don't want to resize the entire image structure, but the images I am working with are too large to easily view with cvShowImage. Is there a way to resize their view within the window created by cvShowImage?
|
No there isn't, you will have to create a new image structure and use cvResize.
|
can i use curl's functions to receive clients https connections? i want to write server using libcurl, should i use naked sockets to accept connections? Oficial documentation provides following example:
```
/* read the response */
for(;;)
{
char buf[1024];
wait_on_socket(sockfd, 1, 60000L);
res = curl_easy_recv(curl, buf, 1024, &iolen);
if(CURLE_OK != res)
break;
printf("Received %u bytes.\n", iolen);
}
```
but they always writes clients, not servers...
|
FromLIBCURL - about
libcurl is a free, open source client to get documents/files from servers, using any of the supported protocols.
It is aclientlibrary not an HTTPS server.
|
this is probably an essentially trivial thing, but it somewhat escapes me, thus far..
char * a3[2];a3[0] = "abc";a3[1] = "def";char ** p;p = a3;
this works:
printf("%p - \"%s\"\n", p, *(++p));
this does not:
printf("%p - \"%s\"\n", a3, *(++a3));
the error i'm getting at compilation is:
lvalue required as increment operand
what am i doing wrong, why and what is the solution for 'a3'?
|
a3 is a constant pointer, you can not increment it. "p" however is a generic pointer to the start of a3 which can be incremented.
|
Is there any method inCcan find a text within another text?
For example,text = "abaHello",textneedtoSearch = "Hello";.
If thetextcontains"Hello",return true, else return false.
|
Usestrstr, seehttp://pubs.opengroup.org/onlinepubs/9699919799/functions/strstr.html
|
I am trying to parse Photoshop PSD files and I want to extract layer information, including text.
Is there any API in Objective-C that can help me to extract this information from PSD files?
|
There is no framework or 3rd party parser available for parsing the PSD file in Objective-C
But there is one available in C language, Which you could use with your objective-C code
Forum Source:
Is there a PSD file parser for Objective-C? I want to replace a layer image and output the result as an NSImage.
load layers from a psd file at runtime?
PSD file parser source code in C.
|
I have C/Java knowledge but i never understand yet, how some hardwares show there own screens/graphics from poweron stage to user interface (where it never shows linux/unix boot screen nor it shows windows booting screens).
My question is, Compared to VCR/TV digicoders poweron till user interfaces, how its made? Do we use regular linux kernel or is there any special open source framework which allow us to develop such?
Thanks
|
Many embedded systems useu-bootas a boot loader. U-boot provides the ability to display a"splash" screenwhile the linux kernel is booting.
|
Do different threads within a single process have distinct independent file descriptor tables? If multiple threads within the same process concurrently access a single file, will the offset into the file for two different calls toopenperformed by different threads be thread-specific?
|
No, there is only one file descriptor table per process, and it's shared among all the threads.
From your problem description, you might want to look into the pread() and pwrite() functions.
|
Is there a secure alternative tomkdir()for C? I am examining some code and notice it is using calls tomkdir(). From what I have read on the US-CERT Secure Coding site, use of that function leaves it vulnerable to "Time of Check, Time of Use" (TOCTOU).
Edit
From the miniunz.c source for zlib
```
int mymkdir(dirname)
const char* dirname;
{
int ret=0;
#ifdef WIN32
ret = mkdir(dirname);
#else
#ifdef unix
ret = mkdir (dirname,0775);
#endif
#endif
return ret;
}
```
Themkdirabove is what I am referring to.
|
Your question is a little vague; a reference to the US-CERT document and some sample code would be nice.
Nevertheless, I bet the answer ismkdirat().
|
I want to write a program (create an exe file) to uninstall a program in WM 5.0. I was searching in Google but nothing really show a step by step how to do this. I had a step by step instruction on how to install a cab file programmatically, but I can't find something similar to unistall the program. I have seen some suggestions to use DMProcessConfigXML but I never used XML before and it will be nice if anyone could show me how to use it.
|
Try to readthisarticle. If I understood correctly what you need is to pass configuration xml toProcessConfigurationmethod.
I hope it helps.
|
In WinAPI is there a mouse move notification for the full desktop (full screen) and not for a window only?
I would like to receive mouse screen coordinates in my main window procedure.
Edit:
What I try to do is getting the coordinates from the mouse when dragging from a button in my window to outside that window.
|
Not as such, no. If you wanted to do something anywhere on the desktop from within your program, e.g. point somewhere or draw something anywhere, you could capture the mouse and then follow the movement until the mouse button is released. SeeSetCapturefor this.
For an example, see this article on MSDN:Drawing Lines with the Mouse
Otherwise you can always useWindows hooksto follow mouse movements anywhere.
|
Compilers these days tend to do a significant amount of optimizations. Do they also remove unused functions from the final output?
|
It depends on the compiler. Visual C++ 9 can do that - unusedstaticfunctions are removed at compilation phase (there's even aC4505 warningfor that), unused functions with external linkage can be removed at link phasedepending on linker settings.
|
i need to add some files to results returned by FindFirstFile and FindNextFile under windows. Is this possible by file system filter driver or what type of drivers?
Thank you
|
You can do this by File System Filter Driver. But you can do this by implementing a system wide API hook. I have not tried it before but you really don't need to take the pains of writing the drivers and making the system unstable in case of spoiling the driver stack.
System Wide API Hooking
API Hooking Revealed
|
I have to do a sign extension for a 16-bit integer and for some reason, it seems not to be working properly. Could anyone please tell me where the bug is in the code? I've been working on it for hours.
```
int signExtension(int instr) {
int value = (0x0000FFFF & instr);
int mask = 0x00008000;
int sign = (mask & instr) >> 15;
if (sign == 1)
value += 0xFFFF0000;
return value;
}
```
The instruction (instr) is 32 bits and inside it I have a 16bit number.
|
Why is wrong with:
```
int16_t s = -890;
int32_t i = s; //this does the job, doesn't it?
```
|
Is callingpthread_exitexplicitly from the thread routine required?
Example code:
```
pthread_create(&pth, NULL, (void *)func, parg);
... func() {
...
//do I have to call pthread_exit() here?
return 0;
}
```
|
Thepthread_createdocumentation says:
If the start_routine returns, the effect is as if there was an implicit call to pthread_exit() using the return value of start_routine as the exit status.
So no, no need to call it explicitly.
|
I have a server application with a listening socket opened on a specific IP port.
How can I allow the socket to enable incoming connections from just one specified IP address?
|
You'll have to either use some firewall software to restrict incoming requests to that port, or shut down accepted connections that you do not want to service (based on the socket address returned byaccept).
There might be libraries out there that do that for you, but the socket API doesn't have anything to do it automatically.
|
I try to get product of two matrix say A and B into C using cblas provided by intel MKL.
Is there any reason for this to be result in error?
```
double * A, *B, *C;
A = (double *) calloc(20 * 200, sizeof (double));
B = (double *) calloc(200 * 200, sizeof (double));
C = (double *) calloc(20 * 200, sizeof (double));
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,
20, 200, 200,
1.0, A, 20,
B, 200,
0.0, C, 20);
```
|
Double check all the parameters to cblas_dgemm. If you have a mistake, the function could be reading beyond the bounds of the array. For small sizes that won't trigger a fault, since the bad addresses will still fall inside a single memory page. (But the math will be wrong, you should check it.) But a 200x200 matrix is 2.5 megabytes of data, passing the wrong size will definitely trigger a segfault.
|
I'm trying validate an X.509 certificate received over a network. I have understood that the digital signature is created by creating a message digest of the fields(don't know which fields) in the signature and then encrypting it using the CA(Certificate Authority) private Key.We can validate the certificate by decrypting the digital signature using CA public key and comparing it with the message digest of the certificate fields.
I'm stuck at this point as I don't know which all fields I should take to create the message digest for the validation. Can somebody please help me out
|
From a glance atthe RFCit appears to be the wholetbsCertificatefield.
[...] a digital signature computed upon
the ASN.1 DER encoded tbsCertificate. The ASN.1 DER encoded
tbsCertificate is used as the input to the signature function.
|
I recently wrote a small C code which uses sockets to listen on a port. It simply echos back the request made to it by a browser. It creates a thread for daemon process and also for servicing new requests. I am doing it simply to learn more about webservers in general. I wanted to know what to do ahead?
I was planning to read the RFC for http. Many questions already answered on StackOverflow suggest going through open source webserver like apache or lighthttp, but I dont know how to start reading such open source projects?
|
Thisis a really good book on HTTP. I recommend getting started with that then maybe the relevant RFC's. Also maybe check out the source oflibcurl, a c library for http, https, ftp etc. Hope this helps :)
AlsoTiny HTTPdis a small http server someone wrote for a school project, you can learn a lot from the source from that.Thisis simple http client in c.
|
we use One-Time initialization for pthreads like this:
```
/* define a statically initialized pthread_once_t variable */
pthread_once_t once_var = PTHREAD_ONCE_INIT;
/* we call pthread_once function in threads */
int pthread_once(pthread_once_t *once_control, void (*init)(void));
```
when more than one thread is going to change the state ofpthread_once_tvariable, do we need a mutex for protecting it?
|
No, you don't need a mutex for this. Thepthread_oncecall (link here) is guaranteed to be executed once and once only, even if multiple threads try it at the same time.
It's theonce_varthat's protecting the call from being executed more than once. It will work as expected, provided that you:
initialise theonce_vartoPTHREAD_ONCE_INIT; andensure thatonce_varis not of automatic storage duration (eg, on the stack); andhave all threads use the sameonce_varvariable.
|
Does there exist a way to allocate some memory and have some sort of callback (be it pointer to a function or signal) when the memory is being accessed (either read or written to)?
For example, if I said allocate 1mb of memory, I would like to have a way to call a function when any of that 1mb is being accessed.
The platform I'm working on is x86 Linux and writing in C/C++.
|
Yes, there is.
Use the mprotect(2) system call (see:http://linux.die.net/man/2/mprotect) to set read only or no access memory protection on the page and set a SIGEGVsignal handler that will be called when the memory has been accessed.
Note that you will need to use mprotect in your signal handler to actually allow the memory access once your signal handler is called and when you do you open a window to anything else to access the memory without you knowing it, for example from a different thread. This may or may not be an issue depending on your specific usage.
|
```
struct tm *localtime(const time_t *timep);
```
I checkedman localtimebut there's no words on whether it's my duty to clean it after using.
And in fact I have many similar doubts on functions returning a pointer, how do you determine it should be freed or not ?
|
This information should be in the man page - mylocaltimeman page says:
The return value points to a
statically allocated struct...
Statically allocated objects should not be passed tofree(), so this is your answer - no, you shouldnotfree the return value oflocaltime().
The only way to tell in the general case is to consult the documentation or implementation of the function in question.
|
```
#if (NGX_SOLARIS)
ngx_int_t i;
size_t size;
#endif
```
I know thatNGX_SOLARISis finally determined when we run./configure,but how are these macros actually defined,can you provide a detailed example that demonstrates how most./configureworks?
|
./configureruns through all the checks for what your system's platform is, what capabilities your compiler has, etc. and then it usesautomaketo generate Makefiles with stuff likeCPPFLAGSwhich define the macros it needs to pass to the preprocessor during compilation.
This is all part of the GNU build system:http://developers.sun.com/solaris/articles/gnu.html
|
```
(gdb) p (char*)0x7fffffffe9c8
$16 = 0x7fffffffe9c8 "\363\353\377\377\377\177"
```
It doesn't look like ascii nor multibyte,what's that?
|
These areoctalcharacter escapes. They are usually used to insert bytes into a string that don't have a meaning as text or need to have a certain binary value.\377for instance is the hexadecimal valueffor decimal255which would be thisÿin ASCII but most likely has a very different meaning in this context.
|
I have a server application with a listening socket opened on a specific IP port.
How can I allow the socket to enable incoming connections from just one specified IP address?
|
You'll have to either use some firewall software to restrict incoming requests to that port, or shut down accepted connections that you do not want to service (based on the socket address returned byaccept).
There might be libraries out there that do that for you, but the socket API doesn't have anything to do it automatically.
|
I try to get product of two matrix say A and B into C using cblas provided by intel MKL.
Is there any reason for this to be result in error?
```
double * A, *B, *C;
A = (double *) calloc(20 * 200, sizeof (double));
B = (double *) calloc(200 * 200, sizeof (double));
C = (double *) calloc(20 * 200, sizeof (double));
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,
20, 200, 200,
1.0, A, 20,
B, 200,
0.0, C, 20);
```
|
Double check all the parameters to cblas_dgemm. If you have a mistake, the function could be reading beyond the bounds of the array. For small sizes that won't trigger a fault, since the bad addresses will still fall inside a single memory page. (But the math will be wrong, you should check it.) But a 200x200 matrix is 2.5 megabytes of data, passing the wrong size will definitely trigger a segfault.
|
I'm trying validate an X.509 certificate received over a network. I have understood that the digital signature is created by creating a message digest of the fields(don't know which fields) in the signature and then encrypting it using the CA(Certificate Authority) private Key.We can validate the certificate by decrypting the digital signature using CA public key and comparing it with the message digest of the certificate fields.
I'm stuck at this point as I don't know which all fields I should take to create the message digest for the validation. Can somebody please help me out
|
From a glance atthe RFCit appears to be the wholetbsCertificatefield.
[...] a digital signature computed upon
the ASN.1 DER encoded tbsCertificate. The ASN.1 DER encoded
tbsCertificate is used as the input to the signature function.
|
I recently wrote a small C code which uses sockets to listen on a port. It simply echos back the request made to it by a browser. It creates a thread for daemon process and also for servicing new requests. I am doing it simply to learn more about webservers in general. I wanted to know what to do ahead?
I was planning to read the RFC for http. Many questions already answered on StackOverflow suggest going through open source webserver like apache or lighthttp, but I dont know how to start reading such open source projects?
|
Thisis a really good book on HTTP. I recommend getting started with that then maybe the relevant RFC's. Also maybe check out the source oflibcurl, a c library for http, https, ftp etc. Hope this helps :)
AlsoTiny HTTPdis a small http server someone wrote for a school project, you can learn a lot from the source from that.Thisis simple http client in c.
|
we use One-Time initialization for pthreads like this:
```
/* define a statically initialized pthread_once_t variable */
pthread_once_t once_var = PTHREAD_ONCE_INIT;
/* we call pthread_once function in threads */
int pthread_once(pthread_once_t *once_control, void (*init)(void));
```
when more than one thread is going to change the state ofpthread_once_tvariable, do we need a mutex for protecting it?
|
No, you don't need a mutex for this. Thepthread_oncecall (link here) is guaranteed to be executed once and once only, even if multiple threads try it at the same time.
It's theonce_varthat's protecting the call from being executed more than once. It will work as expected, provided that you:
initialise theonce_vartoPTHREAD_ONCE_INIT; andensure thatonce_varis not of automatic storage duration (eg, on the stack); andhave all threads use the sameonce_varvariable.
|
Does there exist a way to allocate some memory and have some sort of callback (be it pointer to a function or signal) when the memory is being accessed (either read or written to)?
For example, if I said allocate 1mb of memory, I would like to have a way to call a function when any of that 1mb is being accessed.
The platform I'm working on is x86 Linux and writing in C/C++.
|
Yes, there is.
Use the mprotect(2) system call (see:http://linux.die.net/man/2/mprotect) to set read only or no access memory protection on the page and set a SIGEGVsignal handler that will be called when the memory has been accessed.
Note that you will need to use mprotect in your signal handler to actually allow the memory access once your signal handler is called and when you do you open a window to anything else to access the memory without you knowing it, for example from a different thread. This may or may not be an issue depending on your specific usage.
|
```
struct tm *localtime(const time_t *timep);
```
I checkedman localtimebut there's no words on whether it's my duty to clean it after using.
And in fact I have many similar doubts on functions returning a pointer, how do you determine it should be freed or not ?
|
This information should be in the man page - mylocaltimeman page says:
The return value points to a
statically allocated struct...
Statically allocated objects should not be passed tofree(), so this is your answer - no, you shouldnotfree the return value oflocaltime().
The only way to tell in the general case is to consult the documentation or implementation of the function in question.
|
```
#if (NGX_SOLARIS)
ngx_int_t i;
size_t size;
#endif
```
I know thatNGX_SOLARISis finally determined when we run./configure,but how are these macros actually defined,can you provide a detailed example that demonstrates how most./configureworks?
|
./configureruns through all the checks for what your system's platform is, what capabilities your compiler has, etc. and then it usesautomaketo generate Makefiles with stuff likeCPPFLAGSwhich define the macros it needs to pass to the preprocessor during compilation.
This is all part of the GNU build system:http://developers.sun.com/solaris/articles/gnu.html
|
```
(gdb) p (char*)0x7fffffffe9c8
$16 = 0x7fffffffe9c8 "\363\353\377\377\377\177"
```
It doesn't look like ascii nor multibyte,what's that?
|
These areoctalcharacter escapes. They are usually used to insert bytes into a string that don't have a meaning as text or need to have a certain binary value.\377for instance is the hexadecimal valueffor decimal255which would be thisÿin ASCII but most likely has a very different meaning in this context.
|
Is it possible to declare an array of pointers and later on initialize either of them and assign a value, in aCheader file?
```
char *i[2];
i[0] = "abc";
```
the following does not work.
```
char *x = "def"; // this will, of course.
```
How am I supposed to declare and assign values for an array of pointers?
|
This has nothing to do with header files. You cannot create a .c file and put in it code like this:
```
char *i[2];
i[0] = "abc";
```
In C, all code except definitions and initialisations must be inside functions, and your second statement is neither of these - it is an assignment.
An initialisation for your array would look like this:
```
char *i[2] = {"foo","bar"};
```
And that could be put in a header file, but would cause multiple definition errors if the header were used in more than one translation unit.
|
In C, how can I copy a string with begin and end indices, so that the string will only be partially copied (from begin index to end index)?
This would be like 'C string copy'strcpy, but with a begin and an end index.
|
Usestrncpy
e.g.
```
strncpy(dest, src + beginIndex, endIndex - beginIndex);
```
This assumes you've
Validated thatdestis large enough.endIndexis greater thanbeginIndexbeginIndexis less thanstrlen(src)endIndexis less thanstrlen(src)
|
consider the following two code:
```
void PrintLetter(char *src)
{
while(*src != '\0')
{
printf("%c",*src);
src++;
}
}
```
and
```
void PrintLetter(char *src)
{
int i;
for(i=0;src[i];i++)
printf("%c",src[i]);
}
```
Is there any performance difference between the two?
|
None whatsoever. The compiler will perform its optimizations regardless of the form you are writing. The underlying assembly code is the same.
|
I was reviewing some code and I saw someone do a
```
if (0 == strcmp(foo,""))
```
I am curious because I think it would be faster to do a
```
if (foo[0] == '\0')
```
Is this correct or is strcmp optimized enough to make them the same.
(I realize that even if there was some difference it would be small, but am thinking you save at least a few instructions by using my method.)
|
You're right: since callingstrcmp()adds up the stack management and the memory jump to the actual strcmp instructions, you'll gain a few instructions by just checking the first byte of your string.
For your curiosity, you can check the strcmp() code here:http://sourceware.org/git/?p=glibc.git;a=blob;f=string/strcmp.c;h=bd53c05c6e21130b091bd75c3fc93872dd71fe4b;hb=HEAD
(I thought the code would be filled with#ifdefand obscure__GNUSOMETHING, but it's actually rather simple!)
|
The two declarations are as follows:
```
int (*p)[8];
int *p[8];
```
|
The first is asinglepointer to an array of 8 integers, while the second is anarrayof 8 pointers, each to an integer.
If you just kick upcdecl, it's wonderful for this sort of thing:
```
pax$ cdecl
Type `help' or `?' for help
cdecl> explain int (*p)[8];
declare p as pointer to array 8 of int
cdecl> explain int *p[8];
declare p as array 8 of pointer to int
cdecl> explain char*(*fp[])(int,float*);
declare fp as array of pointer to function (int, pointer to float)
returning pointer to char
```
There's actually aclockwise/spiral ruleyou can use to do this in your head but I haven't had to worry about that since I discoveredcdecl, for the same reason I no longer convert large arbitrary 32 bit numbers from decimal to hex in my head any more - Icanif I have to but it's so much easier with a tool :-)
|
sorry i modified the code now:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
int i=0;
char** f=NULL;
char* ff=NULL;
ff="abcd";
f=( char**)malloc ((i + 1) * sizeof (char *)+5);
f[0]=ff;
// strcpy(f[0],ff); (this again giving same error)
strncat(f[0],"efg",3);
printf("f : %s",f[0]);
}
```
I am getting some unhandled exception, Access violation writing error. Can anyone explain me the error I did here.
NOTE : sorry i modified the code now:
Thanks for the answers
|
you are setting f<-ffff points to the start of a constant char[] ("abcd")
and then you change the value of *f (which is exactly *ff) thus - access violation.
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago.
```
int i = 1;
while (i < n/2)
{
i = i * 2;
int j = i;
while (j > 1)
--j;
}
```
|
O(n):outer loop runslogntimes, in each iteration: i=1,2,4,8,...n/4 (entrance values)inner loops runs2*itimes (entrance values)so at overall you get:2+4+8+...+n/2 = n-2 = O(n)
|
After callingfork, the current process will callexit(0).
But the child will continue.
```
switch(fork())
{
case -1:
exit(1);
case 0:
// child process continues
break;
default:
// the current process exits
exit(0);
}
```
How can I continue debugging the child process in this case?
|
Look atthis. Use:
```
set follow-fork-mode <mode>
```
Set the debugger response to a program call of fork or vfork. A call to fork or vfork creates a new process. The<mode>argument can be:
parent: The original process is debugged after a fork. The child process runs unimpeded. This is the default.
child: The new process is debugged after a fork. The parent process runs unimpeded.
|
```
umask(0);
fd = open("/dev/null", O_RDWR);
```
Here'sman 2 umask:
```
umask() sets the calling process’s file mode creation mask (umask) to mask & 0777.
```
But it doesn't make sense for me,as when we callopen,we will also provide a mode parameter.
So what's the point ofumask?
|
The umask is applied to all modes used in file system operations. From the manualopen(2):
The permissions of the created file are(mode & ~umask)
So with a single call to umask, you can influence the mode of all create files.
This is usually used when a program wants the user to allow to overrule the default grants for files/directories it creates. A paranoid user (or root) can set the umask to0077which means that even if you specify0777inopen(2), only the current user will have access.
|
```
ngx_int_t ngx_daemon(ngx_log_t *log)
{
int fd;
switch (fork()) {
case -1:
ngx_log_error(NGX_LOG_EMERG, log, ngx_errno, "fork() failed");
return NGX_ERROR;
case 0:
break;
default:
exit(0);
}
```
It seems pointless to me,as it only changes the pid,nothing else.
What's the benifit ?
|
The process becomes detached from the terminal so that when the user that started it quits his session, the process remains running.
Daemonizing is not only about the fork, it involves callingsetsid(2)in the child process that detaches the process from the controlling terminal. If you runpsyou can see such processes marked with a?in the tty column.
Also, when you start a daemon it returns the control to the shell right after the fork, rather than the shell having to wait for the process to terminate.
|
I would be interested in answers for both Linux and NT (or any other for that matter)
Edit:
Thanks Laurion for the answer.
More information here:
http://www.symantec.com/connect/articles/dynamic-linking-linux-and-windows-part-onehttp://www.symantec.com/connect/articles/dynamic-linking-linux-and-windows-part-two
|
The runtime loader normally fixes up references to imported functions when the module is loaded. It looks at the table of imported functions and puts in the proper address. The module uses the imported functions through an indirection table.
|
I'm learning C/C++ right now and I am reading about file operations. Suppose a program A is working with an external file (say, a text file) and another another program B is, say, trying to move the file (or worse, delete it). Is it possible to tell the OS to inform the program B that the file is in use, even though it was not created by program A?
|
What you're trying to do is calledfile locking. Search for "file locking in C".
|
How can I get the address of a multidimensional static array?
For example, this is my array
```
char array[2][10] = {"word1", "word2"};
```
Is it possible to get the address to make me reference this array using a pointer like this?
```
char** pointer;
```
I tried &array or directly pointer = (char**)array; but it crashes at startup.
|
char **pointermeans that a pointer is pointing to a pointer.
So*pointeris expected to be a pointer (e.g. 4-byte value which can be interpreted as an address).
This is not the case with your array: it is a contiguous area in memory (20 bytes).
So when you try to convert the array tochar **your application crashes.
It's not possible to do this conversion,char **must point at a pointer.
|
Im writing timers manager in C, which involves:
creating new timerremoving timersremoving dead timerfreezing timersand all the other stuff which i did not yet think about.
The key is - amount of memory should be as small as possible.
At first i thought about linked list, but if i remove some of the middle part, i should rebuild list, which can take some time. Typical dynamic array is the same - i should be carefull with pointers to not miss some of them, when Im rebuliding that structure.
Any ideas ?
Thx for all answer
|
You don't need to rebuild anything when removing from a linked list. It's anO(1)op. No matter what structure you'll choose you'll probably have to be careful about pointers.
|
I'm very new to C. I want to add two one dimensional integer array namea[10] b[10].
I want to put the result in a 2dimentional arrayc[5][2]like
```
c[i][j] = a[i]+b[i];
```
But if I use 2forloops then how can I accessa[9],b[9]value. So I want to use a singleforloop which performa[i]+b[i]and puts the result inc[i][j].
Can anyone tell me how to do this?
How do I put the value in 2dimensional array using single for loop?How do I print the value of 2dimensional array using single for loop?Please don't mind my English or question formatting as I'm very poor at English.
|
if i undersood your problem, you can do this:
```
int col=0; //col counter
int row=0; // row counter
for(int x=0;x<9;x++)
{
if(col>x/2) // check the end of row
{
row++; // increment row
col=0; // reset col counter
}
c[row][col]=a[x]+b[x]; // assignement
col++;
}
```
|
I have been asked in an interview why there is a need of calculating the size of the address to which it is bound in bind system call.
```
bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr))
```
Means i would like to know what is purpose of having third argument in bind system call??
|
Because thesockaddrstructure serves more or less as a "base" structure for "derived" structures likesockaddr_in. It'salmostan inheritance mechanism.
sockaddrcontains variable-length data that can be used by "derived" structures likesockaddr_*, hence you need to precise the effective size of the "derived" structure.
|
I have 2 variables:
```
int a;
char b[10];
```
I want to combine/append both data in one array:
```
temp[50];
```
How can I do that?
|
You didn't give us enough information about the type of temp or why you want to do that, generally it doens't make much sense to combine types. However if temp is a char array and you want to concatenate both of them for some kind of useful output, you can use sprintf:
```
int a = 10;
char b[10] = "apple";
char temp[50];
sprintf(temp, "%d %s", a, b);
/* 10 apple */
puts(temp);
```
%din the sprintf is used to represent a decimal integer while%sis use to represent a null-terminated string.
|
I have grown accustomed tostrtodand variants.
I am wondering why there is nostrtoishipped with<stdlib.h>.
Why is it that the integer type is left out of this party?
Specifically I am asking why there is not a version ofatoiwith the safety features ofstrtod?
|
strtol()converts a string to an integer, a long integer but an integer nevertheless. There isatoi()but it should be avoided in most cases due to the fact that it lacks a mechanism for error reporting from invalid input.
|
I've just written a function that returns a pointer to a block of memory allocated by malloc. If I call free() on the returned pointer, will this free the memory?
I tried reading up on this, but I can't find anything that says whether you can call a different pointer pointing to the same location and whether that will free all the memory or not.
This is probably majorly basic, I think I can't find the info because I'm searching for it wrong.
Any help appreciated!
|
Yes callingfreewill free the memory. Its not the pointer that get freed but the memory that the pointer points to that is freed.
|
I am wondering how to implement a bubble sort on a singly-linked list. Let's say for example that we have list that consists of following nodes:
```
struct node {
int value;
struct node* next;
}
```
I believe that there are 2 ways to acomplish this:
```
1)to directly exchange `values` in memory
2)to change `nexts`, to point to a different nodes
```
Which way is more efficient, and can somebody give me some example on how to do it? I'm aware that using Bubble Sort isn't very efficient compared to other sorting algorithms.
|
Your values are very small, so I expect exchanging them to be more efficient than changing the pointer structure. As always, you will have to measure the actual performance in your use case to be sure.
|
So I'm having trouble getting even a simple Makefile to work. Heres what I have:
```
proj : driver.o
icc -g -O3 -openmp driver.o -o proj
driver.o : driver.c driver.h
icc -g -O3 -openmp driver.c
```
I feel like it's pretty straight forward. Proj only depends on driver.o which in turn depends on driver.c and driver.h. When run, the compiler fails with 'could not open source file "driver.h" ' at the include within the driver.c file. What am I missing?
|
You should giveicca-I.option to get it to look for include files in the current directory.
```
icc -I. -c -g -O3 -openmp driver.c
```
(I took the liberty of also adding the-cflag to prevent linking.)
|
I have 2 variables:
```
int a;
char b[10];
```
I want to combine/append both data in one array:
```
temp[50];
```
How can I do that?
|
You didn't give us enough information about the type of temp or why you want to do that, generally it doens't make much sense to combine types. However if temp is a char array and you want to concatenate both of them for some kind of useful output, you can use sprintf:
```
int a = 10;
char b[10] = "apple";
char temp[50];
sprintf(temp, "%d %s", a, b);
/* 10 apple */
puts(temp);
```
%din the sprintf is used to represent a decimal integer while%sis use to represent a null-terminated string.
|
I have grown accustomed tostrtodand variants.
I am wondering why there is nostrtoishipped with<stdlib.h>.
Why is it that the integer type is left out of this party?
Specifically I am asking why there is not a version ofatoiwith the safety features ofstrtod?
|
strtol()converts a string to an integer, a long integer but an integer nevertheless. There isatoi()but it should be avoided in most cases due to the fact that it lacks a mechanism for error reporting from invalid input.
|
I've just written a function that returns a pointer to a block of memory allocated by malloc. If I call free() on the returned pointer, will this free the memory?
I tried reading up on this, but I can't find anything that says whether you can call a different pointer pointing to the same location and whether that will free all the memory or not.
This is probably majorly basic, I think I can't find the info because I'm searching for it wrong.
Any help appreciated!
|
Yes callingfreewill free the memory. Its not the pointer that get freed but the memory that the pointer points to that is freed.
|
I am wondering how to implement a bubble sort on a singly-linked list. Let's say for example that we have list that consists of following nodes:
```
struct node {
int value;
struct node* next;
}
```
I believe that there are 2 ways to acomplish this:
```
1)to directly exchange `values` in memory
2)to change `nexts`, to point to a different nodes
```
Which way is more efficient, and can somebody give me some example on how to do it? I'm aware that using Bubble Sort isn't very efficient compared to other sorting algorithms.
|
Your values are very small, so I expect exchanging them to be more efficient than changing the pointer structure. As always, you will have to measure the actual performance in your use case to be sure.
|
So I'm having trouble getting even a simple Makefile to work. Heres what I have:
```
proj : driver.o
icc -g -O3 -openmp driver.o -o proj
driver.o : driver.c driver.h
icc -g -O3 -openmp driver.c
```
I feel like it's pretty straight forward. Proj only depends on driver.o which in turn depends on driver.c and driver.h. When run, the compiler fails with 'could not open source file "driver.h" ' at the include within the driver.c file. What am I missing?
|
You should giveicca-I.option to get it to look for include files in the current directory.
```
icc -I. -c -g -O3 -openmp driver.c
```
(I took the liberty of also adding the-cflag to prevent linking.)
|
So I have some specific environment (like linux os based phone) so I have no such thing like terminal. All I can do is create my own UI's using C++ and some SDK I am provided with.
I want to create an ssh client application for my device. Its not a work, nor a homework - just for fun that means I have lots of time for solving conflicts that may appear.
My main problem is I have never worked withOpenSSHas a lib... and when I look on it it seems some large mountain to me.
So I ask for your help - have you seen any open-source ssh clients that use SSH methods with their own UI's based on OpenSSH or, betterPortable OpenSSH?
|
PuTTYfor example.
|
I'm developing an app in C using Gtk. I have a GtkCombo with some restrictions that should launch an error message when user selects wrong entries in the list. The problem is that when callback launches the error message, pop-down string is still open, and if the user moves the mouse over it, the list acts as if all entries under the mouse pointer where clicked. This behavior stops if the user clicks on an empty window area or other GtkWidget. I've tried changing the focus to another widget, launching button_release signal...
Anyone knows how to prevent this bug?
|
Try connecting the signal withg_signal_connect_after()instead ofg_signal_connect(). The callback should run after the combo popdown has finished all its reactions to the click.
|
I have a
```
structure {
int a;
char b;
} st;
```
Is there a way to typecast the structure memberst.a?
Because in few places I want it asintand in few places I want it asChar*
|
I suggest to use aunion:
```
struct {
union {
int a;
char *ptr;
} u;
char b;
} st;
```
Under the assumption thatsizeof(int) == sizeof(char*)holds, you can access the same value in memory by either usingst.u.aorst.u.ptr.
For what it's worth, consider usingsize_tinstead ofintas the type of theafield. That way, your code will still be correct in 64bit builds (in which anintmay still be 32bit but a pointer is 64bit).
|
So I am writing a C file which includes /extfs/ext2fs.h. I am trying to call the function ext2fs_open(). I can clearly see that the header file ext2fs.h has that particular function. In fact, if I pass in the incorrect number of arguments, it even corrects me. However it does not compile, always giving me a "undefined reference" error. This problem lies with all the methods defined in the header file. How am I supposed to compile this file? Is there some library I need to link to?
Thank you.
|
You do need to link tolibext2fs, yes...
```
gcc -I/dir/containing/ext2fs.h -lext2fs your_source.c -o app
```
|
```
typedef struct {
float *numbers;
float val1;
float val2;
} Values;
Values val[16];
```
How can one allocate memory for numbers in the struct?
|
If you want to allocate the space for one float in the first element of your struct, you would do it like this:
```
#include <stdlib.h>
/* ... */
val[0].numbers = malloc(1 * sizeof(float)); /* "1 * " for clarity... */
```
If that's what you meant.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.