question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
How can I get theASCIIrepresentation of hexadecimal values in the memory by examining ingdb?
The gdb commandx/[repeatCount] [memoryAddress]gives me hexadecimal 32-bit values starting atmemoryAddressrepeatCounttimes but I want the readable text/String which is represented by this data. How do I do that?Thispage doesn't seem to tell.
For instance I get the following by examining:
```
0x41414141
```
What I want to see instead or as well is this:
```
AAAA
```
Like an ordinaryHex <-> ASCII converter.
|
Nevermind, I need to use theformat lettersforString.
```
x/[repeatCount]s [memoryAddress]
```
Found by typing
```
help x
```
and reading the help documentation. <_<
|
I am compiling some project with dependency so i won't have to recompile each time, but when i am adding -Dsome_flags to my CFLAGS, it is not recompiling.
```
dep: $(CPPS)
$(CC) $(CFLAGS) $(INC) -M $(CPPS) > dep
```
i add to my CFLAS -DDEBUG_FLAG and it forces me to do make clean and make instead of make.
|
It won't recompile because you don't have the makefile itself listed as a dependency.
```
dep: $(CPPS) Makefile
$(CC) $(CFLAGS) $(INC) -M $(CPPS) > dep
```
That said, if you're feeding in make flags from the command line (e.g.CFLAGS=-O3 make all),makehas no way of detecting that you've changed those and forcing a full build.
|
I am trying to compile old project, but I got an error. That project implements functiondprintf, which is some kind of aprintffunction. However when I tried to compile that project today I found out thatdprintfis already defined instdio.h. So my question is - how to hide the standarddprintffunction, because now I'm constantly getting an error like this:
```
ntreg.c:82: error: conflicting types for 'dprintf'
/usr/include/stdio.h:397: note: previous declaration of 'dprintf' was here
ntreg.c:93: error: conflicting types for 'dprintf'
/usr/include/stdio.h:397: note: previous declaration of 'dprintf' was here
```
|
dprintf()is not defined by the Standard.
If you configure your compiler for Standard C, the function should no longer be exposed
```
gcc -std=c99 -pedantic ...
```
|
I have a string with some spaces on the end. I would like to terminate this string at the position when the first space occurs, so that when I later dostrncpy()on it, it would copy only the part of the string which doesn't contain spaces.
This is some try which gives me a segault obviously. How can I do what I intend to do?
```
int main() {
char* s1 = "SomeString ";
*(s1 + 10)='\0';
printf("%s\n",s1);
return 0;
}
```
|
Modifying the content of a literal string like you do in*(s1 + 10)='\0';is undefined behavior.
|
I am reading a book called "beginning linux programming". I would like to ask about this line of code (from page 204):
```
if (output_stream) putc(char_to_write, output_stream);
```
I can't understand this line.
any help will be greatly appreciated.
|
In
```
if (output_stream) putc(char_to_write, output_stream);
```
if(output_stream)is a condition. Ifoutput_streamis notNULL, then theputcwill execute.
The functionputcwith declarationint putc (int char, FILE *stream)writes a character (anunsigned char) specified by the argumentcharto the specifiedstreamand advances the position indicator for the stream.In short, it writes a character(first argument) to its second argument.
|
I have an Android Studio project that uses NDK
and I can't get include paths to work.
let say I have app/src/main/jni/foo/bar/file.c
and it includes "my/lib/inc.h"
When I add
LOCAL_C_INCLUDES += /home/user/include/ (to app/src/main/jni/Android.mk)
where the folder "my" is located I still get file not found from ndk-build
If I add "my" to app/src/main/jni it works fine.
What am I missing?
|
Android studio is probably ignoring your Android.mk and generating its own.
At the present instant in time, the NDK isn't well supported by Android Studio, and although you will find various version-specific gradle rule modifications which have apparently worked for their authors, it may be easier build the NDK code yourself and merely let the packaging stage pickup the results.
|
I'd like to enable multi line commenting support in my Atom editor. I'd like the editor to automatically add a*and a proper indentation at the beginning of new lines of a multiline comment. Here's a sample of what I'm looking for:
```
/***
* This is a comment
* when I'm adding a new line it automatically adds " * ".
*/
```
I've tried to look for such package in the Atom package search, on the SO and google but I failed to find anything. I must have typed wrong key words.
I know that geany editor has such a feature so I guess that Atom has one as well.
|
So, I didn't know that the keyswords should beblock comment.
I managed to find an excellent extension which is described asa helper package for writting documentation.
One way or another it does what I was looking for.Here is a link to the repo:https://github.com/nikhilkalige/docblockr
|
When I write software in C, should I putstaticandinlinefunctions in the.hor in the.cfile?
|
Do not put the declaration nor definition of astaticfunction (or variable) in a.hfile. That defeats the points ofstatic- keeping functions/variables local.
inlineis another matter - it depends on the scope meant for the function. Aninlinefunction in a.his meant for global usage and scope. Aninlinefunction in a.cis meant for local usage only. This is much the same strategy as would be used for a#define
inlinefunctions can beextern,staticor unspecified.@Christophwell explainsinlinescope issues.
|
I currently have a short program to read and sort a text tile in C.
If I want to read many files, is there a substitute for:
FILE *f
f = fopen("*.txt", "rw");
Thanks in advance.
|
f = fopen("*.txt", "rw"); won't work in any case.
The usual way to do this probably depends on your operating system. On Unix-like systems, the simple way is to invoke your program with a command line like "my_pgm *.txt" and let the shell find the matching files. (You'll get multiple arguments, each one being a file name.) I understand that microsoft OSes would require the program to find the files itself.
To do that more or less portably, I'd probably use opendir() and readdir() to examine directory entries and see whether they matched the desired pattern.
|
Is it possible to divide in linux kernel and use double values?
When I tried:
```
typedef struct{
...
long long int sbe;
...
} connection;
hook_func(){
connection* found
...
uint32_t time_misec ..
uint32_t bytes_diff ..
...
double be = bytes_diff / time_misec;
found->sbe = be / 2 + found->sbe / 2;
...
}
```
I got errors:
```
WARNING: "__fixunsdfsi" [/home/kir/netfilter/hello.ko] undefined!
WARNING: "__adddf3" [/home/kir/netfilter/hello.ko] undefined!
WARNING: "__floatdidf" [/home/kir/netfilter/hello.ko] undefined!
WARNING: "__muldf3" [/home/kir/netfilter/hello.ko] undefined!
WARNING: "__floatunsidf" [/home/kir/netfilter/hello.ko] undefined!
```
|
For most CPU, there is no floating point support in the Linux kernel. The reason is to avoid the high cost of saving FPU registers.
|
Sorry if the topic name isn't very clear I couldn't find a way to express it.
So let's say i have this structure :
```
struct filee
{
...
int number;
char filename[7];
};
typedef struct filee filee;
```
and I want to initialize it with a function
```
void file_init(filee* x,int n)
{
x->number=n;
x->filename=(char)n+"ch.bmp"
}
```
but that doesn't really work so what I want is if for example I do this :
```
file_init(&randomFile,2);
```
It works this way:
```
randomFile.number=2;
randomFile.filename="2ch.bmp";
```
I hope that what I said is clear and thanks for the help!
|
You need to usesnprintf()
```
int length;
int result;
length = sizeof(x->filename);
result = snprintf(x->filename, length, "%dch.bmp", x->number);
if ((result < 0) || (result >= length))
error_TheTargetIsNotLargeEnough();
```
|
I currently have a short program to read and sort a text tile in C.
If I want to read many files, is there a substitute for:
FILE *f
f = fopen("*.txt", "rw");
Thanks in advance.
|
f = fopen("*.txt", "rw"); won't work in any case.
The usual way to do this probably depends on your operating system. On Unix-like systems, the simple way is to invoke your program with a command line like "my_pgm *.txt" and let the shell find the matching files. (You'll get multiple arguments, each one being a file name.) I understand that microsoft OSes would require the program to find the files itself.
To do that more or less portably, I'd probably use opendir() and readdir() to examine directory entries and see whether they matched the desired pattern.
|
Is it possible to divide in linux kernel and use double values?
When I tried:
```
typedef struct{
...
long long int sbe;
...
} connection;
hook_func(){
connection* found
...
uint32_t time_misec ..
uint32_t bytes_diff ..
...
double be = bytes_diff / time_misec;
found->sbe = be / 2 + found->sbe / 2;
...
}
```
I got errors:
```
WARNING: "__fixunsdfsi" [/home/kir/netfilter/hello.ko] undefined!
WARNING: "__adddf3" [/home/kir/netfilter/hello.ko] undefined!
WARNING: "__floatdidf" [/home/kir/netfilter/hello.ko] undefined!
WARNING: "__muldf3" [/home/kir/netfilter/hello.ko] undefined!
WARNING: "__floatunsidf" [/home/kir/netfilter/hello.ko] undefined!
```
|
For most CPU, there is no floating point support in the Linux kernel. The reason is to avoid the high cost of saving FPU registers.
|
Sorry if the topic name isn't very clear I couldn't find a way to express it.
So let's say i have this structure :
```
struct filee
{
...
int number;
char filename[7];
};
typedef struct filee filee;
```
and I want to initialize it with a function
```
void file_init(filee* x,int n)
{
x->number=n;
x->filename=(char)n+"ch.bmp"
}
```
but that doesn't really work so what I want is if for example I do this :
```
file_init(&randomFile,2);
```
It works this way:
```
randomFile.number=2;
randomFile.filename="2ch.bmp";
```
I hope that what I said is clear and thanks for the help!
|
You need to usesnprintf()
```
int length;
int result;
length = sizeof(x->filename);
result = snprintf(x->filename, length, "%dch.bmp", x->number);
if ((result < 0) || (result >= length))
error_TheTargetIsNotLargeEnough();
```
|
I have this php code
```
<?php
$Command = "cd /var/www/html/Codiad/workspace/workspace 2>&1; gcc HelloWorld.c; ./a.out"
$Method1 = exec($Command);
echo $Method1;
?>
```
The code works fine, it shows the output, but I want only see the output after click on a button. How can I do that remaining on the same page? To be more precise I have two buttons, one for compiling code and one for execute it.
|
I suggest you do it with AJAX and make 2 calls. One button clicks makes request that will compile. Other will execute the code.
|
This question already has answers here:C: unary minus operator behavior with unsigned operands(4 answers)Closed8 years ago.
My C compiler gave a warning when using unary minus on anunsignedvalue, so I fixed the warning by doing a subtraction from 0 instead.
Now I wonder if the current code is equivalent to the original one:
```
uint32_t a, b; // assume b is initialized and non-zero
a = -b % b; // old code
a = (0-b) % b; // current code
```
My question is: for the same values ofbwill both lines of code yield the same result fora?
|
Usually, yes, unless on your platformuint32_twould be a narrow type. Then it would first be promoted tointand the negation would be made in that type.
|
```
#include <stdio.h>
main()
{
char buf[8];
sprintf(buf,"AAAA%3s","XXssssssssXXXsssssXXX");
printf("%s\n",buf);
}
```
I expected valgrind to detect a buffer overflow with the above code. But it does not report any errors or warnings. Do I need to enable any special flags for that?
|
FromValgrind Tutorial
What valgrind is NOT
Although valgrind is an extremely useful program, it will not miraculously tell you about every memory bug in your program. There are several limitations that you should keep in mind. It does not do bounds checking on stack/static arrays ..
|
This question already has answers here:C: unary minus operator behavior with unsigned operands(4 answers)Closed8 years ago.
My C compiler gave a warning when using unary minus on anunsignedvalue, so I fixed the warning by doing a subtraction from 0 instead.
Now I wonder if the current code is equivalent to the original one:
```
uint32_t a, b; // assume b is initialized and non-zero
a = -b % b; // old code
a = (0-b) % b; // current code
```
My question is: for the same values ofbwill both lines of code yield the same result fora?
|
Usually, yes, unless on your platformuint32_twould be a narrow type. Then it would first be promoted tointand the negation would be made in that type.
|
```
#include <stdio.h>
main()
{
char buf[8];
sprintf(buf,"AAAA%3s","XXssssssssXXXsssssXXX");
printf("%s\n",buf);
}
```
I expected valgrind to detect a buffer overflow with the above code. But it does not report any errors or warnings. Do I need to enable any special flags for that?
|
FromValgrind Tutorial
What valgrind is NOT
Although valgrind is an extremely useful program, it will not miraculously tell you about every memory bug in your program. There are several limitations that you should keep in mind. It does not do bounds checking on stack/static arrays ..
|
Dynamic memory allocation in C/C++ happens throughmallocand the static memory allocation ex:int a[3];its allocated after the code is executed.
But this codeint x[y+1];only can happen after a value is attributed to y and this happens in execution time, so its static, dynamic or both? does the compiler insert a malloc in the machine code automatically?
|
It is a Variable Length Array (VLA). Wikipedia:http://en.wikipedia.org/wiki/Variable-length_array
Technically, it is not legal in C++, but compilers often support it as an extension, but generate warnings when they are turned on. SeeWhy aren't variable-length arrays part of the C++ standard?
It is legal in C.
|
If I usefgets()to store a line into an array of characters with a size that is greater than the number of characters what happens to the empty indexes between the last character entered and the string terminator?
For example:
If I use thefgetsfunction to scan in a word entered by the user without knowing the length of the word then I have to use an arbitrary length of something like 80 to ensure the word will fit.
```
fgets(word, 80, stdin);
```
but say the user enters: "hello"
This word is only 5 characters (7 with '\0' and '\n'), so what happens to the other 73?
|
The first 7 characters get filled with'h' , 'e' , 'l' , 'l' , 'o' , '\n' , '\0'The rest are left as they were.
|
So I have an unsigned integer Q with the value of 0xfccd11c0.
When I print it withprintf("%i", Q);I get -53669440 which is the signed integer representation of 0xfccd11c0 so I get it.
But when I print it withprintf("%i", (double)Q);I get 939524096. I DO know that in order to print a double value you need to use%fas the string format, but still, what happens when converting to double that is causing that value to be printed?
|
Q is 4241297856
(double)Q has 64-bit IEEE-754 representation 0x41EF99A238000000
In little-endian, the lower 4 bytes of this occupy the same space as (int)Q would.
0x38000000 is 939524096
Handy online converter:http://babbage.cs.qc.edu/courses/cs341/IEEE-754.html
|
I have some code in C that expects char buffer that looks like this:
```
char buf[ 64 ];
buf[0] = 0x01;
buf[1] = 0x11;
buf[2] = 0x61;
buf[3] = 0x08;
buf[4] = 0x01;
```
I am trying to create this buffer in Python, and pass the pointer to the C code. I created buf as follows,
```
buf = create_string_buffer('0x01 0x11 0x61 0x08 0x01', 64)
```
but when I pass the pointer to my C code, it looks like the C code is reading the ASCII code for 01, not a hex literal.
How do I fix this?
|
In Python hex literals are escaped by\x
so in your case the string to pass into your c function would be written as
```
'\x01\x11\x61\x08\x01'
```
There is a tableherein the python2 docs listing the escape sequences that python understands (correspondinglinkfor python3).
|
I mean is there a possibility to print a string like ("hello") to i.e. just "e" or "l".
I thought i could accomplish that with this code:
```
char *gg = "hello";
printf("%.4s \n",gg + strlen(gg) - 2);
```
but it doesn't work.
|
You will want to do the following:
```
char *gg = "hello";
printf( "%c\n", gg[3] );
```
This will print the fourth character (zero based array = 0, 1, 2, 3 so 0='h', 1='e', etc). Change the 3 to which ever character you want, but make sure to not go past the end of the string. strlen will tell you the length of the string.
|
The following function checks if a variable name start with a letter and may have preceding characters which are letters/ numbers. Why does the return value is always 1 no matter what the input is?
```
#include <regex.h>
#include <stdio.h>
int validate_var(char *str)
{
regex_t reg;
regcomp(®, "^[a-zA-Z]+[a-zA-Z0-9]*$", 0);
int r = regexec(®, str, 0, NULL, 0);
regfree(®);
return r;
}
int main() {
printf("%d\n", validate_var("abc")); // Reports 1, This makes sense
printf("%d\n", validate_var("17")); // Reports 1, This doesn't make sense
}
```
|
You're using anchors (^and$) but not enabling extended syntax by passingREG_EXTENDEDtoregcomp().See the manual page.
You should really check all return values, there should be a failure reported somewhere due to the syntax usage error.
Note that non-zero means failure.
|
The standard functionstrstris used to find the location of a sub-string in a string. Both the arguments of the function are ofconst char *type, but the return type ischar *.
I would like to know how a standard function is implemented violating the const-correctness.
|
All theconst char *is telling you is thatstrstris not going to modify the string you pass into it.
Whether you modify the returned string or not is up to you as it is your string!
In C++ this has been changed by overloading the method and having two versions, theconstinput version has aconstoutput.
In C it doesn't have quite that level of safety built in for you and assumes you know yourself whether you should be modifying the returned string.
|
i read already some answers on stackoverflow but I don't know why it still doesn't work :
```
typedef struct gnl_struct {
char *data;
int where;
int status;
} t_gnl;
void display_elem(t_gnl tab, int nbr)
{
printf("tab[%d]\n", nbr);
printf("tab.where == %d\n", tab.where);
printf("tab.status == %d\n", tab.status);
return ;
}
int main()
{
static t_gnl tab[1000] = {{ "toto", 0, 2 }} ;
display_elem(tab[3], 3);
return (0);
}
```
the result is :
```
tab[3]
tab.where == 0
tab.status == 0
```
|
In your code, you've (yourself) initalized onlytab[0]and you're passingtab[3]. All the otherelementsin the array [tab[1]totab[999]] areautoinitalized to0.
|
I'm building a project in Xcode 6.3. I based it on acommand line toolproject template. Is there a possibility to exclude the automatically added libraries of such paths and origins like for examplecurses.h?Here the path:/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/curses.h
Where can I change the default settings of inclusion/exclusion of the default libraries loaded in the target of my project?
Thank you for any hints, since it is awfully hard to find something about it on the web.
|
It turns out that you can easily disable all the additional modules in Xcode'sBuild Settings:
Build Settings > Apple LLVM 6.1 - Language - Modules > Enable Modules (C and Objective-C)
and set it toNo.
(a broader answer was posted by Thomas Dickey here:How to disable "curses.h" header (a part of "stdio.h in Xcode 6.3 OSX Yosemite) to avoid conflicting function declarations)
|
I have come across some code where it looks like this.
```
while(1, N)
```
whereNcan an integer ranging from 0 - 100.
Can somebody tell how can we use while loop like that.
|
As per theC11standard document, chapter 6.5.17, comma operator,
The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.
So, essentially,
```
while(1, N)
```
is same as
```
while(N)
```
|
I'm trying to open a tempfile using
```
fd = open("/tmp", O_RDWR | O_TMPFILE, 0);
if (fd == -1) {
perror("open()");
exit(1);
}
```
and I am getting "open(): Permission denied".
I have permissions in /tmp:
```
drwxrwxrwt 13 root root 1.2K Apr 23 13:55 /tmp/
```
and I believe my kernel is new enough for O_TMPFILE:
```
Linux frosties 3.14-1-amd64 #1 SMP Debian 3.14.2-1 (2014-04-28) x86_64 GNU/Linux
```
What am I missing?
|
The call failed because you have specified mode0, which means no permissions. Seethis LWN articlefor a discussion of this behavior of the Linux kernel, and an apparent bugfix.
|
```
#include<stdio.h>
void main ()
{
int a=4;
const int *p=&a;
*p--;
}
```
in the above line it means that we can not change the value a via p, so in decrement statement it should give an error but it is not giving the error. can anyone explain why??
|
*p--decrementspnot contents ofp.
If you do(*p)--you will get compilation error
```
error: decrement of read-only location ‘*p’
```
|
Is there a way to manually do print elements of *char arrays as hex values without introducing loops or affecting the pointers by incrementation?
It should not add introduce additional variables, change current ones and should be a onelinerprintf/printk/...
|
No loops, pointer and size are constant parameters effectively:
```
void fun( char * ptr, uint idx, uint size )
{
if( idx < size )
{
printf( "% 2x\n", ( unsigned char ) ( ptr[idx] ) );
fun( ptr, 1 + idx, size );
}
}
```
Example invocation:
```
char ray[] = { 0xca, 0xff, 0xee, 0x00 };
fun( ray, 0, sizeof( ray ) / sizeof( ray[0] ) );
```
|
Will any of the standard C library behavior be affected by GCC version? One example I am interested in isstrncpy()but any other examples would be interesting too.
|
Will any of the standard C library behavior be affected by GCC version?
Yes, but depends.
It's quite a broad question. There are differences in what gcc supports depending on what version of gcc you are using. gcc has many extensions which are not in standard C (hence not portable if you use those extensions). You could disable most of them with-std=xx -pedantic-errorsflag. Assuming you have a gcc version that supports all standard C features(whatever standard you aim for), then additional differences between Standard C vs. POSIX C vs. GNU C vs. Linux specific extensions are usually documented in the manual, which you could consult to determine potential differences or extensions. As for strncpy, there's no difference in behaviour between standard C and GNU C.
|
I know compiler does Structure padding because CPU can read one word at time ( Word size depends on architecture 16/32/64 ) but I am not able to understand padding behavior for below example.
```
struct pad
{
char ch;
};
```
Size of "struct pad" comes as 1 Byte ( But According to padding concept I suspected 4 byte ( 32 bit architecture ).
|
A char type can be accessed efficiently on any address boundary, so no padding is necessary.
|
i am building a program that copies directories to each other, but i can only get it to work hard coded.
i want the directory to be input by the user via a command line argument.
i have used
```
char SrcPath[] = argv[1];
```
however when i hard code it like
```
char SrcPath[] = "home/user/Desktop/cat"; it works fine.
```
but this doesn't work, can anybody explain why / suggest a way to do this?
and is there a special way that directories have to be input when used in a CLI?
|
Making the change tochar *SrcPath = argv[1];should work. Pointers and arrays are different things!
|
I'm new to c programming. I'm trying to print numbers 1 to 10.
```
#include <stdio.h>
int main(){
int i;
for(i=1; i<11; i++){
printf("%s\n", i);
}
getchar();
}
```
It compiles in powershell when I type:gcc .\forloop.cbut when I try to run the program with./aI get this error message:
Any help would be appreciated.
|
```
printf("%s\n", i);
```
That tries to print a string.iis an integer. So it will crash when it dereferencesias a string.
Try
```
printf("%d\n", i);
```
|
I'm trying to do thisswprintf(hexResult, L"%I64X", result);from javascript, is this possible? Such thatCityHash64('C:\Program Files (x86)\Mozilla Firefox')is encoded asE7CF176E110C211B.
Thanks
|
JavaScript numbers have atoStringmethod which takes a radix. UsingtoString(16)will get you the number in hex. Is this what you're looking for?
|
I am trying to do calculation with a 2D matrix. Why does this crash without an error?
Code:
```
int main (void)
{
int myArray[2][3] = {{1,2,3},{5,4,3}};
int height = 2;
int width = 3;
modifyArray( (int**)myArray,height, width);
}
void modifyArray(int **array, int height1, int width1)
{
int result;
for(i=0;i<height1;i++)
{
for(j=0;j<width1;j++)
{
result = (**((array+i*3)+j));
printf("%d", result)
}
}
}
```
|
The cast to( int ** )is forcing myArray to be treated as an array of pointers to int.
That's not what it is - it's a single chunk of memory the compiler treats as a 2-dimensional array.
|
This is my code.
```
#include<stdio.h>
typedef struct {
int a,b;
} integers;
void main() {
integers *ptr = (integers *)malloc(10*sizeof(integers));
printf("%d",sizeof(*ptr)); // prints 8
}
```
From what I understand about Malloc, the above code should actually reserve 10x8=80 bytes of memory for ptr to point to.
Why then does using sizeof(*ptr) give only 8? How do I find the total size being allocated for ptr?
|
Because you're usingsizeof(*ptr)you're actually asking for the size of the first element in the allocated buffer, thussizeofwill return the size of thefirst element inptr(i.e. 2x4 bytes integers on 32bits system) rather than the allocated size.
Also, please note that even if you'd usesizeof(ptr)you'd get the size of theptrpointer which on 32bits system would be 4 bytes.
|
I'm using while(getchar()!='\n') to empty my stdin, but sometimes if I want to go on, I need to push on Enter key and so the computation continue... Why? I'll post part of my code:
```
while(1){
if(fgets(buffer,MAX_DIMENSION,stdin)==NULL){ perror("Error"); exit(1);}
}else{
printf("Not correct term\n");
while(getchar()!='\n');
sleep(1);
}
}
```
thanks!
@iharob if i set MAX_DIMENSION=1240 and I send as input: a string > 1024 it remains something on stdin, so I have to use while(getchar()!='\n')
|
You have usedfgetsto get a string. That string was terminated by the newline characters. Then, you are trying toemptystdinby usinggetcharand to get something intogetchar, you have to input another newline character. You can simply ignore the buffer afterfgetsif that is what you wanted. There is no need to usegetcharto empty the buffer.
|
One of my assignments for the C Programming course was define a function called create_card. This function receives a suit character and an a card value, and returns a card_t struct.
Question: How is a function supposed to create a struct? Can't it only create values for the struct? Did I misinterpret the meaning of the question or was the assignment written down wrong?
|
This is an example of a function returning a struct.
```
struct test {
int a;
};
struct test Fun(int k) {
struct test d;
d.a=k;
return d;
}
```
Replacestruct testwith the name of your struct and the definition ofstruct testwith your struct's definition.
How to use
```
int main() {
struct test Test=Fun(6);
printf("%d",Test.a); // prints '6'
return 0;
}
```
|
How can I delete the first digit of a given number using a user defined function (Suppose the function isDELTOP) ?
For Ex.,
```
x=DELTOP(1748);
```
I want the value ofxas748.
Would anybody tell me how to write this function easily ?
|
A C++11 one-liner would be
```
int DELTOP(int x) {
return std::stoi(std::to_string(x).substr(1));
}
```
|
I know that calloc allocates memory and writes zeroes to each cell, so my question is:
is there a difference between using calloc or using malloc and running over the cells writing NULL to them? Are the zeroes of calloc equivalent to NULL?
|
No, they are notalwaysequivalent, but on most popular machines you'll be fine.callocwrites a bit pattern of all-zeros to the allocated memory, but the null pointer value might not be all-bits-zero on some machines (or even just for some types on some machines).
Check out theNull Pointerssection of the C FAQ for lots and lots of information.
|
I've used the code below but it is giving me an result of file path.
```
status = FltGetFileNameInformation(Data,
FLT_FILE_NAME_OPENED |
FLT_FILE_NAME_QUERY_ALWAYS_ALLOW_CACHE_LOOKUP,
&nameInfo);
DbgPrint("\n Filename : %wZ",&nameInfo->Name);
```
```
\Device\HarddiskVolume1\Users\filename.ext
```
But I want the file path as I
```
c:\Users\Filename.ext
```
How can I get this please help.
|
```
NameLength = (USHORT)dosName.MaximumLength + Data->Iopb->TargetFileObject->FileName.MaximumLength + 2;
NameBuffer = ExAllocatePoolWithTag(PagedPool,NameLength,NC_MAPPING_TAG);
NameString.Length = 0;
NameString.MaximumLength = NameLength;
NameString.Buffer = NameBuffer;
RtlCopyUnicodeString(&NameString, &dosName);
RtlAppendUnicodeStringToString(&NameString, &Data->Iopb->TargetFileObject->FileName);
```
|
Does something like TextBox exist in ncurses?
Requirements to TextBox:
ability to adequate handle KEY_DOWN, KEY_UP, KEY_LEFT, KEY_RIGHT, KEY_BACKSPACE, KEY_DC and other.adequate transfer lines.save, if you need, text in char* buffer.
|
ncursesitself provides lower-level functions from which a "textbox" can be built. For instance, thedialogandcdklibraries use (n)curses to provide these features.
|
I had some doubts about fopen...
Can i perform the following?
```
fopen("%temp%" , "r");
```
or do i need to use windows specific functions?
|
No, you cannot do directly (unless you want to open file called%temp). There is a functionExpandEnvironmentStringsthat does that:
```
char path[MAX_PATH];
ExpandEnvironmentStrings("%TEMP%\\tempfile", path, MAX_PATH);
fopen(path, "r");
```
You can do that manually -- in this case it can be more portable:
```
char path[MAX_PATH];
const char* temp = getenv("TEMP");
if(temp == NULL)
; // Return an error or try to guess user's Temp
// directory with GetUserProfileDirectory or similiar functions
snprintf(path, MAX_PATH - 1, "%s\\tempfile", temp);
fopen(path , "r");
```
But there is acleaneroption for your case --tmpfile
|
I know that calloc allocates memory and writes zeroes to each cell, so my question is:
is there a difference between using calloc or using malloc and running over the cells writing NULL to them? Are the zeroes of calloc equivalent to NULL?
|
No, they are notalwaysequivalent, but on most popular machines you'll be fine.callocwrites a bit pattern of all-zeros to the allocated memory, but the null pointer value might not be all-bits-zero on some machines (or even just for some types on some machines).
Check out theNull Pointerssection of the C FAQ for lots and lots of information.
|
I've used the code below but it is giving me an result of file path.
```
status = FltGetFileNameInformation(Data,
FLT_FILE_NAME_OPENED |
FLT_FILE_NAME_QUERY_ALWAYS_ALLOW_CACHE_LOOKUP,
&nameInfo);
DbgPrint("\n Filename : %wZ",&nameInfo->Name);
```
```
\Device\HarddiskVolume1\Users\filename.ext
```
But I want the file path as I
```
c:\Users\Filename.ext
```
How can I get this please help.
|
```
NameLength = (USHORT)dosName.MaximumLength + Data->Iopb->TargetFileObject->FileName.MaximumLength + 2;
NameBuffer = ExAllocatePoolWithTag(PagedPool,NameLength,NC_MAPPING_TAG);
NameString.Length = 0;
NameString.MaximumLength = NameLength;
NameString.Buffer = NameBuffer;
RtlCopyUnicodeString(&NameString, &dosName);
RtlAppendUnicodeStringToString(&NameString, &Data->Iopb->TargetFileObject->FileName);
```
|
Does something like TextBox exist in ncurses?
Requirements to TextBox:
ability to adequate handle KEY_DOWN, KEY_UP, KEY_LEFT, KEY_RIGHT, KEY_BACKSPACE, KEY_DC and other.adequate transfer lines.save, if you need, text in char* buffer.
|
ncursesitself provides lower-level functions from which a "textbox" can be built. For instance, thedialogandcdklibraries use (n)curses to provide these features.
|
I had some doubts about fopen...
Can i perform the following?
```
fopen("%temp%" , "r");
```
or do i need to use windows specific functions?
|
No, you cannot do directly (unless you want to open file called%temp). There is a functionExpandEnvironmentStringsthat does that:
```
char path[MAX_PATH];
ExpandEnvironmentStrings("%TEMP%\\tempfile", path, MAX_PATH);
fopen(path, "r");
```
You can do that manually -- in this case it can be more portable:
```
char path[MAX_PATH];
const char* temp = getenv("TEMP");
if(temp == NULL)
; // Return an error or try to guess user's Temp
// directory with GetUserProfileDirectory or similiar functions
snprintf(path, MAX_PATH - 1, "%s\\tempfile", temp);
fopen(path , "r");
```
But there is acleaneroption for your case --tmpfile
|
At the third line I get "Expected a declaration" for instr[0xB8][256]
```
void funcB8 ();
void (*instr[256][257])();
instr[0xB8][256] = &funcB8;
```
|
You can initialize the array at a specific index outside a function:
```
void (*instr[256][257])() = { [0xB8][256] = &funcB8 };
```
or assign a value to the array, but to do that you have to do that in a function
|
Consider the following code sample:
```
#define STRING_LITERAL "%u, %u"
const char string_const[ ] = "%u, %u";
snprintf(dest_buff, sizeof(dest_buff), STRING_LITERAL, arg1, arg2, arg3);
```
My compiler then issues a Warning: the format string ends before this argument
Now if I change the instruction to:
```
snprintf(dest_buff, sizeof(dest_buff), string_const, arg1, arg2, arg3);
```
Then no warning is issued by the compiler.
My question is: does such a behavior comply with the C99 standard?
|
The warning is generated by the compiler which was able to determine that you passed incorrect arguments to the call, and didn't in the second.
The standard defines that passing incorrect arguments and/or using incorrect flags results in undefined behavior.
The warning is not required by the Standard, and it is merely additional help to the programmer.
|
This question already has answers here:Is a string literal in С++ created in static memory?(4 answers)Where are static variables stored in C and C++?(16 answers)Closed8 years ago.
How does memory gets allocated for a string literal in C and do we need to free it?
E.g.:
```
char *k="hello world";
```
Where does this string get stored and how does it get de-allocated?
|
where does this string get stored
Usually in read-only memory, you cannot modify it. Ingcc, on most systems, they are located in the.TEXTsection.
how does it get de-allocated
upon program termination.
|
This is simple code. In which I am taking a input, printing it, and taking again and printing it once more.
For the second time it doesn't let me give the input.
Can someone explain why ?
```
#include "stdio.h"
int main()
{
char buff[50];
printf("Enter a String\n");
scanf("%[^\n]s",buff);
puts(buff);
printf("Enter another String\n");
scanf("%[^\n]s",buff);
puts(buff);
return 0;
}
```
Output :
```
Enter a String
Hello // This I have entered
Hello // This is the output
Enter another String
Hello // This I haven't entered, It automatically takes this.
```
|
In the second scanf(), place a space at the beginning of your input specifier:
```
scanf(" %[^\n]s",buff);
^^^
```
This willeatthe character that is currently satisfying scanf the second time, and allow you to enter a second string.
|
So, I'm trying to write some JNA code to work with Unix sockets, and I'm trying to reference AF_UNIX for sockets. I looked through some of the gcc included files, but I couldn't find anything.
|
It may be platform-dependent, which is why you should use the define. It should be insys/socket.h.
|
I have a function that return1 Byte
```
uint8_t fun();
```
the function should run 9 times , so I get 9 Byte I want to make the last8one as4 short valueshere what I've done but I'm not sure that the value that I get are correct :
```
char array[9];
.............
for ( i = 0; i< 9 ; i++){
array[i] = fun();
}
printf( " 1. Byte %x a = %d , b=%d c =%d \n" ,
array[0],
*(short*)&(array[1]),
*(short*)&(array[3]),
*(short*)&(array[5]),
*(short*)&(array[7]));
```
is that right ?
|
It's better to be explicit and join the 8-bit values into 16-bit values yourself:
```
uint8_t bytes[9];
uint16_t words[4];
words[0] = bytes[1] | (bytes[2] << 8);
words[1] = bytes[3] | (bytes[4] << 8);
words[2] = bytes[5] | (bytes[6] << 8);
words[3] = bytes[7] | (bytes[8] << 8);
```
The above assumes little-endian, by the way.
|
I would like to change the values in mychar *to the int and double that are declared so I can change them without touching char *sql.
(on ubuntu using C)
How can i do this?
code:
```
int sensor_id = 10;
double temp = 22.22;
char *sql = "INSERT INTO test_table(sensor_id, sensor_value) VALUES(10, 22.22)";
```
|
Try this (dirty, no error checking, buffer overflow may occur):
```
const char *sqlformat =
"INSERT INTO test_table(sensor_id, sensor_value) VALUES(%d, %f)";
char sql[200];
sprintf(sql, sensor_id, temp);
```
Now you have what you want in thesqlbuffer.
This is very basic C stuff, I suggest you to learn C.
|
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.Closed8 years ago.Improve this question
Can some one tell me, how to get remote host MAC address by using its ip address in linux by using c programming(could be netlink sockets or BSD sockets)?
|
This can't be done using C programming. If it was possible then there wouldn't be any protocol likeARPto get the link layer address.
You can implement ARP request and reply using socket programming. But that's not what you want in this case I think. Anyway in that case you can refer to this discussionlink.
You can have a look at this for that purposesource code.
|
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.Closed8 years ago.Improve this question
Explain the return type of the function given below and how to call this fuction
```
// C function to search a given key in a given BST
struct node* search(struct node* root, int key)
{
// Base Cases: root is null or key is present at root
if (root == NULL || root->key == key)
return root;
// Key is greater than root's key
if (root->key < key)
return search(root->right, key);
// Key is smaller than root's key
return search(root->left, key);
}
```
|
Function's return type isstruct node*, i.e. a pointer tostruct nodetype. It will return a node for a given key.
You can call it as
```
search(root, key); // 'root' is root of the tree and 'key' is the data you want to search.
```
|
I am trying to write a packet sniffer in C. To identify ARP packets, I have defined a structure where the 16 bit integer gives me a hex value which I can compare with the library definition of ARP, i.e ETH_P_ARP from where I can confirm if the packet is ARP.
Structure:
```
struct ethernet {
unsigned char dest[6];
unsigned char source[6];
uint16_t eth_type;};
```
I want to do something similar for DHCP, but I am not able to identify it.
|
Look for UDP traffic between ports 67 (server) and 68 (client). Seethis Wikipedia entryfor the packet encoding details.
|
I'm writing a netfilter module and need to store current time value somewhere inside the module to calculate difference in time. What is the best way to do that?
|
I didn't understood your question properly. Because you are not provided any piece of code. Any way you can keep your variable either indevice structure of module, or you can declare variable simply as aGlobal variable.
|
The following C code is apparently O(N) (according to my practice exam). However, I am not sure as to why it is O(N) and not O(Something*Something).
```
void doit(int N) {
while (N) {
for (int j = 0; j < N; j += 1) {
}
N = N / 2;
}
}
```
Anyone care to give me some insight to this problem?
Thanks in advance!
|
Because N + N/2 + N/4 + ... = 2N.
|
This question already has answers here:How to execute a shell script from C in Linux?(6 answers)Closed8 years ago.
Is there a way to run command line utilities, e.g.gzip, into a C app?
|
Usesystem():
```
#include <stdlib.h>
int status = system("gzip foo");
```
See the man page (man 3 system) for more detailed information on how to use it.
By the way, this question already has an answer here:How do I execute external program within C code in linux with arguments?
|
I was messing around in C trying to find a way to interpret the difference in memory address' when finding two array elements next to each other and finding the difference. Here's my code:
```
#include <stdio.h>
int main(){
char *a[5];
printf("%p\n", (&a[0]));
printf("%p\n", (&a[1]));
return 0;
}
```
And example output:
```
0xbf9343dc
0xbf9343e0
```
When doing this, shouldn't the output be something to the form:
```
0x0....0
0x0....1
```
Because the size of a char pointer should be 1 (on a 32-bit system which I am using).
If anyone knows why this is the case and can offer an explanation it would be very helpful
|
The size of acharis1, the size of achar *is implementation dependent, usually4in32-bit system.
|
I have following C code:
```
#define total 5
typedef struct data{
int id;
int age;
char name[50];
}groups;
groups people[total];
people[1] = {1, 20, "Joseph"};
```
However I'm getting an error saying
'conflicting types in 'people'
and I don't understand why.
|
Either one of these will work:
```
groups people[total];
people[1] = (groups) {1, 20, "Joseph"};
```
or:
```
groups people[total] = {
[1] = {1, 20, "Joseph"}
};
```
|
```
int u = 21;
int v = 10;
if (u && v) printf(“ Time to move on!! ”);
if (u & v) printf(“Do it today!! \n”);
```
This only prints "Time to move on!!" which makes sense because both u and v are true in the first if statement but for "if (u & v)" I'm not sure how it's determining whether that's true or false. I get it &'s the two binary representations of 21 and 10 but then what? Thanks!
|
21 in binary is10101, whereas 10 in binary is01010. A bitwise&returns00000, or0, which isfalse.
|
This question already has answers here:Is it possible to create a type in c++ that takes less than one byte of memory?(5 answers)Closed8 years ago.
I was wondering if it is possible to create a 23-bit user defined type in c++. I can create a 24-bit type just fine using 3 chars however I am trying to get one bit less. Any suggestions?
|
You can use a bit-field.
```
struct TwentyThreeBits {
int x : 23;
TwentryThreeBits & operator = (int y) {
x = y;
return *this;
}
};
```
This allows you manipulate the memberxas a 23 bit value. The actual size of the type is likely larger (likelysizeof(TwentyThreeBits)is at leastsizeof(int)).
If you would like to represent many items that only occupy 23 bits, you could create an array of bits (either withvector<bool>or withbitset) and access the right multiple of 23 into that array to get to the "object".
|
I was messing around in C trying to find a way to interpret the difference in memory address' when finding two array elements next to each other and finding the difference. Here's my code:
```
#include <stdio.h>
int main(){
char *a[5];
printf("%p\n", (&a[0]));
printf("%p\n", (&a[1]));
return 0;
}
```
And example output:
```
0xbf9343dc
0xbf9343e0
```
When doing this, shouldn't the output be something to the form:
```
0x0....0
0x0....1
```
Because the size of a char pointer should be 1 (on a 32-bit system which I am using).
If anyone knows why this is the case and can offer an explanation it would be very helpful
|
The size of acharis1, the size of achar *is implementation dependent, usually4in32-bit system.
|
I have following C code:
```
#define total 5
typedef struct data{
int id;
int age;
char name[50];
}groups;
groups people[total];
people[1] = {1, 20, "Joseph"};
```
However I'm getting an error saying
'conflicting types in 'people'
and I don't understand why.
|
Either one of these will work:
```
groups people[total];
people[1] = (groups) {1, 20, "Joseph"};
```
or:
```
groups people[total] = {
[1] = {1, 20, "Joseph"}
};
```
|
```
int u = 21;
int v = 10;
if (u && v) printf(“ Time to move on!! ”);
if (u & v) printf(“Do it today!! \n”);
```
This only prints "Time to move on!!" which makes sense because both u and v are true in the first if statement but for "if (u & v)" I'm not sure how it's determining whether that's true or false. I get it &'s the two binary representations of 21 and 10 but then what? Thanks!
|
21 in binary is10101, whereas 10 in binary is01010. A bitwise&returns00000, or0, which isfalse.
|
This question already has answers here:Is it possible to create a type in c++ that takes less than one byte of memory?(5 answers)Closed8 years ago.
I was wondering if it is possible to create a 23-bit user defined type in c++. I can create a 24-bit type just fine using 3 chars however I am trying to get one bit less. Any suggestions?
|
You can use a bit-field.
```
struct TwentyThreeBits {
int x : 23;
TwentryThreeBits & operator = (int y) {
x = y;
return *this;
}
};
```
This allows you manipulate the memberxas a 23 bit value. The actual size of the type is likely larger (likelysizeof(TwentyThreeBits)is at leastsizeof(int)).
If you would like to represent many items that only occupy 23 bits, you could create an array of bits (either withvector<bool>or withbitset) and access the right multiple of 23 into that array to get to the "object".
|
I have following C code:
```
#define total 5
typedef struct data{
int id;
int age;
char name[50];
}groups;
groups people[total];
people[1] = {1, 20, "Joseph"};
```
However I'm getting an error saying
'conflicting types in 'people'
and I don't understand why.
|
Either one of these will work:
```
groups people[total];
people[1] = (groups) {1, 20, "Joseph"};
```
or:
```
groups people[total] = {
[1] = {1, 20, "Joseph"}
};
```
|
```
int u = 21;
int v = 10;
if (u && v) printf(“ Time to move on!! ”);
if (u & v) printf(“Do it today!! \n”);
```
This only prints "Time to move on!!" which makes sense because both u and v are true in the first if statement but for "if (u & v)" I'm not sure how it's determining whether that's true or false. I get it &'s the two binary representations of 21 and 10 but then what? Thanks!
|
21 in binary is10101, whereas 10 in binary is01010. A bitwise&returns00000, or0, which isfalse.
|
This question already has answers here:Is it possible to create a type in c++ that takes less than one byte of memory?(5 answers)Closed8 years ago.
I was wondering if it is possible to create a 23-bit user defined type in c++. I can create a 24-bit type just fine using 3 chars however I am trying to get one bit less. Any suggestions?
|
You can use a bit-field.
```
struct TwentyThreeBits {
int x : 23;
TwentryThreeBits & operator = (int y) {
x = y;
return *this;
}
};
```
This allows you manipulate the memberxas a 23 bit value. The actual size of the type is likely larger (likelysizeof(TwentyThreeBits)is at leastsizeof(int)).
If you would like to represent many items that only occupy 23 bits, you could create an array of bits (either withvector<bool>or withbitset) and access the right multiple of 23 into that array to get to the "object".
|
I have two 32-bit integers and two 16-bit integers. How can I combine them into one 12-byte long array in the kernel?
|
Here's one (C99) way, if you want the machine's native byte ordering:
```
union {
struct {
uint32_t a, b;
uint16_t c, d;
} ints;
char bytes[12];
} tmp;
tmp.ints.a = 0xdeadf00d;
tmp.ints.b = 0xfeedbabe;
tmp.ints.c = 0xfee1;
tmp.ints.d = 0x600d;
```
Now you can access thetmp.bytesarray to get at the bytes that make up the numbers. On ideone,bytescontains:
```
0d f0 ad de be ba ed fe e1 fe 0d 60
```
You might want to add some (compiler-specific) padding instructions to make sure the integers are "packed", too. The above has decent alignment for many compilers, though.
|
I'm creating an application client/server. Users registered are located in their specific file. I need that only one process of my client can login with that specific username. So I think that the best way to handle it, it's to forbid the opening of a file if it's just opened by another process, but I don't know how to do it. Suggestions? Thanks!
I have thought about semaphores but I don't think is the best solution....
ok, I'll use flock() thanks! ^^ But after open() what kind of error will give me?
|
Check out the system command/shell command calledflock.
So as you want only one process accessing the open file, you'll be usingLOCK_EXoperation on the file descriptor (Assuming you're using the system call).
Please go through the man pages.man flockfor shell command andman 2 flockfor the system call.
|
This is my code:
```
//bubble sort
#include<stdio.h>
int main(){
int a[11];
int temp;
int i,j;
//input
for(i=1;i<=10;i++){
scanf("%d",&a[i]);
}
//sort
for(i=1;i<10;i++){ //the number of number
for(j=1;j<10-i;j++) //--
if(a[j]<a[j+i]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
//output
for(i=1;i<=10;i++){
printf("%d ",a[i]);
}
getchar();
getchar();
return 0;
```
}
The result was not what I was expecting. The input that I have used is 1 2 3 4 5 6 7 8 9 0 but after the sort the output is 8 6 5 4 3 7 2 9 1 0.
|
Two things:
A typo (I believe):
```
if(a[j]<a[j+i]){
```
should have been
```
if(a[j]<a[j+1]){
```
Secondly,
```
for(j=1;j<10-i;j++)
```
should have been
```
for(j=1;j<10-i+1;j++)
```
You need to run the loop one extra time, to accommodate all swaps.
Ideone link
|
Can anyone tell where the problem is?
```
someone@someone:~/Desktop$ cat morning.c
```
```
#include <stdio.h>
int main (int argc, char** argv)
{
printf ("Good Morning") ;
return 0;
}
```
```
someone@someone:~/Desktop/9raya$ ./morning.c
./morning.c: line 2: syntax error near unexpected token `('
./morning.c: line 2: `int main (int argc, char** argv)'
```
I really don't see where the problem is.
|
The problem is that you're trying to execute C source code and your shell doesn't understand that. You need to compile the source code into an executable, then execute it. For example,
Compilemorning.cto produce an executable namedmorning:
gcc -Wall -Wextra morning.c -o morning
Executemorning:
./morning
where I added the-Walland-Wextraflags to provide a more useful set of compiler warnings on top of gcc's quite minimal default.
|
I just started programming in C. And I don't really understand the following code:
```
printf("%zu",i);
```
or instead of%zuwhat are the other things that I can write (I know that they depend on the type of i) and which one is for what?
|
It's a format modifier forsiz_tandsize_tis unsigned.
```
printf("%zu\n", x); // print unsigned decimal
printf("%zx\n", x); // print hexadecimal
printf("%zd\n", y); // print signed decimal
```
|
```
typedef struct { int x; int y; } Point_t;
Point_t construct_point(int x, int y); /* takes 2 integers,
returns a Point_t representing
these integers */
```
How can write this function?
|
this is really straightforward:
```
typedef struct
{
int x;
int y;
} Point_t;
Point_t f(int x, int y)
{
Point_t p = { x, y };
return p;
}
```
And (to beat possible comments upfront): no, this is not returning a reference to a local variable.
|
I'm creating an application client/server. Users registered are located in their specific file. I need that only one process of my client can login with that specific username. So I think that the best way to handle it, it's to forbid the opening of a file if it's just opened by another process, but I don't know how to do it. Suggestions? Thanks!
I have thought about semaphores but I don't think is the best solution....
ok, I'll use flock() thanks! ^^ But after open() what kind of error will give me?
|
Check out the system command/shell command calledflock.
So as you want only one process accessing the open file, you'll be usingLOCK_EXoperation on the file descriptor (Assuming you're using the system call).
Please go through the man pages.man flockfor shell command andman 2 flockfor the system call.
|
This is my code:
```
//bubble sort
#include<stdio.h>
int main(){
int a[11];
int temp;
int i,j;
//input
for(i=1;i<=10;i++){
scanf("%d",&a[i]);
}
//sort
for(i=1;i<10;i++){ //the number of number
for(j=1;j<10-i;j++) //--
if(a[j]<a[j+i]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
//output
for(i=1;i<=10;i++){
printf("%d ",a[i]);
}
getchar();
getchar();
return 0;
```
}
The result was not what I was expecting. The input that I have used is 1 2 3 4 5 6 7 8 9 0 but after the sort the output is 8 6 5 4 3 7 2 9 1 0.
|
Two things:
A typo (I believe):
```
if(a[j]<a[j+i]){
```
should have been
```
if(a[j]<a[j+1]){
```
Secondly,
```
for(j=1;j<10-i;j++)
```
should have been
```
for(j=1;j<10-i+1;j++)
```
You need to run the loop one extra time, to accommodate all swaps.
Ideone link
|
Can anyone tell where the problem is?
```
someone@someone:~/Desktop$ cat morning.c
```
```
#include <stdio.h>
int main (int argc, char** argv)
{
printf ("Good Morning") ;
return 0;
}
```
```
someone@someone:~/Desktop/9raya$ ./morning.c
./morning.c: line 2: syntax error near unexpected token `('
./morning.c: line 2: `int main (int argc, char** argv)'
```
I really don't see where the problem is.
|
The problem is that you're trying to execute C source code and your shell doesn't understand that. You need to compile the source code into an executable, then execute it. For example,
Compilemorning.cto produce an executable namedmorning:
gcc -Wall -Wextra morning.c -o morning
Executemorning:
./morning
where I added the-Walland-Wextraflags to provide a more useful set of compiler warnings on top of gcc's quite minimal default.
|
I just started programming in C. And I don't really understand the following code:
```
printf("%zu",i);
```
or instead of%zuwhat are the other things that I can write (I know that they depend on the type of i) and which one is for what?
|
It's a format modifier forsiz_tandsize_tis unsigned.
```
printf("%zu\n", x); // print unsigned decimal
printf("%zx\n", x); // print hexadecimal
printf("%zd\n", y); // print signed decimal
```
|
```
typedef struct { int x; int y; } Point_t;
Point_t construct_point(int x, int y); /* takes 2 integers,
returns a Point_t representing
these integers */
```
How can write this function?
|
this is really straightforward:
```
typedef struct
{
int x;
int y;
} Point_t;
Point_t f(int x, int y)
{
Point_t p = { x, y };
return p;
}
```
And (to beat possible comments upfront): no, this is not returning a reference to a local variable.
|
my C program only outputs 0.000 and i have no idea why
```
#include <stdio.h>
#include <float.h>
int main(){
int count;
double input;
double output = DBL_MAX;
int i;
printf("Enter a positive integer: ");
scanf("%i", &count);
for (i = 0; i < count; i++){
printf("Enter a number:");
scanf("%f", &input);
if(output>input)
{
(output = input);
}
}
printf("The smallest number is: %f", output);
}
```
the code compiles fine but just seems to no either not scan it properly or some other issue i'm just not seeing.
|
The correct specifier for a typedoubleis%lf.
You pass the address of a double variable to scanf() and tell it it is an address of a float%f.
The function then overflows and you get an incorrect result.
|
I am trying to delete a file in c program. Assume that the file is located in current directory of source file. I have searched a lot but didn't get any solution. Everyone is suggesting to useremove()function.
Here is my source code:
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int delete_status;
char del[50];
printf("Enter a file name to delete it: ");
gets(del);
delete_status = remove(del);
if(delete_status!=0) {
printf("File can not be deleted!\nFile does not exist in current directory\n");
}
else printf("File %s has been deleted successfully!\n", del);
return 0;
}
```
Is there any way to remove file without usingremove()function. I want to code manually without using any other stl built in function.
|
You can replaceremove()withunlink()(for files) andrmdir()(for directories).
|
On mac I am using kqueue, it states that udata is unchanged. However the array returned inevent_dataofkeventcall is being modified somewhat. What could cause this? I am passing in the pointer to string casted to void*, and when i read afterkeventafter the first 3 characters the rest are coming out modified.
Thanks
|
The kernel only saves and returns the value of the pointer itself, not the contents of the memory it points to. Chances are that you're passing a pointer to memory that is being overwritten later on.
Thekqueue64()system call is a little bit more explicit about this by defining the field as auint64_t.
|
Why the output of the following program is
```
x = 10 y = 18
```
?
```
int y;
void fun(int x) {
x+=2;
y=x+2;
}
int main() {
int x;
x=10; y=11;
fun(x);
fun(y);
printf("x=%d y=%d\n", x,y);
return 0;
}
```
Shouldn't the output be 10 and 11 ?
|
Sinceyis aglobal variable, in the first callfun(x);ybecomes14sincexis10,x += 2makesx == 12and theny = x + 2which gives14. Then you call it withy == 14, which makes the localxinfun(),x == 16and theny == y + 2which is18.
|
Consider the code, in the C programming language:
```
double d = 3.4;
printf("%02.2f", d);
```
or
```
double d = 3.4;
printf("%2.2f", d);
```
The output you get when running these blocks of code are:
```
3.40
```
I am trying to format a table and need to reserve spaces in front of a double or float so that my tables doesn't draw askew.
What is the best way to obtain the output
```
03.40
```
as intended?
|
```
double d = 3.4;
printf("%05.2f", d);
```
The width field is for the entire converted string (not just the whole number part).
|
How do you resetscanf()to read the beginning of the text without the use offopenorfclose.
I have a stage 1 which reads half of the text file and stage 2 requires me reset thescanf()to beginning of the text and read it all the way.
Any tips or guidance is appreciated.
You Guys are the best!
EDIT: The text has ONLY numbers in it and the file is opened via/myprogram <txt.txt.
|
You can usefseek()orrewind().
```
rewind(fp);
```
or
```
fseek(fp, 0, SEEK_SET);
```
|
In this loop,:
```
for( i = 0; i < N>>1; i++)
```
does the N value shift throughout every repetition? i.e. if N=1024, then the first loop does
```
for( i = 0; i < 512; i++)
```
and the next loop does
```
for( i = 0; i < 256; i++)
```
|
It does not. If you want to do that, then a construct like the following would do that:
```
for( i = 0; i < N; N >>= 1, i++)
```
Or put the shift inside of your loop. The shift operator by itself doesn't change the value of the operand without an assignment statement.
|
I wrote a calculator program in visual studio. But i need it to run with also DEVC++. But my code doesn't work on gcc compiler. Here is a little part of the code that doesn't work.
```
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
int main(){
long double var1 = 0, var2= 0, memory, result;
char wordInput[50] = { 0 };
char *endPtr1, *endPtr2;
printf("Enter an input: ";
scanf("%[^\n]%*c", wordInput);
var1 = strtold(wordInput, &endPtr1);
printf("%.4f", var1);
}
```
This is the block of code where i get the input and convert it to double and assign to the var1. When i compile it with visual studio it works(it prints the number which is entered) but with devc++ it doesn't (it prints 0.0000). What can i do to fix it?
|
try this
```
#define __USE_MINGW_ANSI_STDIO 1
#include <stdio.h>
....
printf("%.4Lf", var1);
```
|
This might be a stupid question, but I really need to know since it's the first time I encounterd this:
```
void function()
{
;
}
```
This is used in a thread based program withpthread. I want to know what it actually does.
I tried looking it up, but I don't even know how to google it.
Thank you for your time.
|
;is a C statement termination construct. Placing it without statement is meaningless and doesn't hurt in code behavior in anyways. In your case, function gets called and returns.
|
```
#include<stdio.h>
main() {
int i=9;
printf("\nAddress of i = %d", &i);
printf("\nAddress of i = %x", &i);
printf("\nAddress of i = %u", &i);
printf("\nAddress of i = %p", &i);
printf("\nValue of i = %d",i);
}
```
When I use%pI get: Value ofi=0xbfd08d5cOther formats%d,%x,%udon't work.
|
In general, you are not allowed to use%d,%x, or%ufor an address. You should use only%p- that is the only valid format to use for pointers.
Moreover, since%pexpects a void pointer, you need to add a cast to&ioperation:
```
printf("\nAddress of i = %p", (void*)&i);
```
Although the code would work without a cast on most platforms, it is a good idea to add a cast to guarantee compatibility with platforms where a pointer to anintand a void pointer have different representations. I am not sure if there are any such platforms, but the standard does not prohibit them.
|
I want to genrerate big random numbers in c. The problem is that the biggest number srand() can generate is about 37000. I want to create a number in the intervall 70000 to 2150000000. Could anyone help me with this.
Random number generator:
```
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main ()
{
srand(time(NULL));
int i;
for (i=0; i<50; i++)
{
int random = rand();
printf("%d\n",random);
}
return 0;
}
```
|
First of all, checkRAND_MAXfor the maximum value that can be generated byrand().
You could compose tworand()results into one value.
```
int random = (rand() << 16) | rand();
```
|
Consider the code, in the C programming language:
```
double d = 3.4;
printf("%02.2f", d);
```
or
```
double d = 3.4;
printf("%2.2f", d);
```
The output you get when running these blocks of code are:
```
3.40
```
I am trying to format a table and need to reserve spaces in front of a double or float so that my tables doesn't draw askew.
What is the best way to obtain the output
```
03.40
```
as intended?
|
```
double d = 3.4;
printf("%05.2f", d);
```
The width field is for the entire converted string (not just the whole number part).
|
How do you resetscanf()to read the beginning of the text without the use offopenorfclose.
I have a stage 1 which reads half of the text file and stage 2 requires me reset thescanf()to beginning of the text and read it all the way.
Any tips or guidance is appreciated.
You Guys are the best!
EDIT: The text has ONLY numbers in it and the file is opened via/myprogram <txt.txt.
|
You can usefseek()orrewind().
```
rewind(fp);
```
or
```
fseek(fp, 0, SEEK_SET);
```
|
In this loop,:
```
for( i = 0; i < N>>1; i++)
```
does the N value shift throughout every repetition? i.e. if N=1024, then the first loop does
```
for( i = 0; i < 512; i++)
```
and the next loop does
```
for( i = 0; i < 256; i++)
```
|
It does not. If you want to do that, then a construct like the following would do that:
```
for( i = 0; i < N; N >>= 1, i++)
```
Or put the shift inside of your loop. The shift operator by itself doesn't change the value of the operand without an assignment statement.
|
I wrote a calculator program in visual studio. But i need it to run with also DEVC++. But my code doesn't work on gcc compiler. Here is a little part of the code that doesn't work.
```
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
int main(){
long double var1 = 0, var2= 0, memory, result;
char wordInput[50] = { 0 };
char *endPtr1, *endPtr2;
printf("Enter an input: ";
scanf("%[^\n]%*c", wordInput);
var1 = strtold(wordInput, &endPtr1);
printf("%.4f", var1);
}
```
This is the block of code where i get the input and convert it to double and assign to the var1. When i compile it with visual studio it works(it prints the number which is entered) but with devc++ it doesn't (it prints 0.0000). What can i do to fix it?
|
try this
```
#define __USE_MINGW_ANSI_STDIO 1
#include <stdio.h>
....
printf("%.4Lf", var1);
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.