question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I have a 2D array calledchar **str(allocated by malloc). Lets say str[0] has the string "hello". How would I print that hex?
I triedprintf("%d\n", (unsigned char)strtol(str[0], NULL, 16)), but that doesn't print it out in hex.
Any help would be appreciated, thank you!
|
You are confused about the fuctionality ofstrtol. If you have a string that represents a number in hex, you can usestrtollike you have:
```
char s[] = "ff2d";
int n = strtol(s, NULL, 16);
printf("Number: %d\n", n);
```
When you want to print the characters of a string in hex, use%xformat specifier for each character of the string.
```
char s[] = "Hello";
char* cp = s;
for ( ; *cp != '\0'; ++cp )
{
printf("%02x", *cp);
}
```
|
For example there is a method dog:
```
void dog(char C,int N)
{
//here if I want to print the value of C with a print statement,how do I do that?
}
```
|
What about a
```
printf("the value of c = %c\n", C);
```
|
I am allowed to use an extra array to perform a stable quicksort unlike the general quicksort algorithm. I know how to select the pivot at random and partition accordingly but I'm not able to figure out how to make use of the additional array to make it stable.
|
The most trivial way that comes to mind is to store the initial indices in the array (1, 2, 3, etc) and swap them around as you swap the data.
Then in the comparison, if the two elements are equal, compare their indices too, thus making it stable.
|
When I open a file in C, I am currently doing this:
```
int main()
{
FILE *f
f = fopen("employers.dat", "rb");
if(f == NULL)
{
PUTS("can not open the file:\"employers.dat\"");
fclose(f);
exit(-1);
}
return 0;
}
```
Is it necessary to usefcloseif the pointer isNULL?
|
Not only it isnotnecessary to usefclose()whenfisNULL, but you should actuallynotinvokefclose()whenfisNULL.
IffisNULL, then the file was never opened to begin with, so it does not need any closing.Even if the file somehow needed closing, the solution could not possibly involve passingNULLtofclose(), because aNULLparameter carries absolutely no information thatfclose()can use to figure out which file to close.I am not sure whetherfclose()contains extra code for detecting and ignoring an erroneousNULLparameter passed to it, but even if it does, it is best to not tempt your fate.
|
I am trying to use POSIX regex in C, but it's not working. Here's my code:
```
int regi(char *c, char *e)
{
regex_t regex;
int reti = regcomp(®ex, e, 0);
reti = regexec(®ex, c, 0, NULL, 0);
if(!reti)
return 1;
return 0;
}
int main()
{
char str[5] = {'0','x','2','F'};
if(regi(str, "^(0[xX])[0-9a-fA-F]+"))
// Do stuff
return 0;
}
```
I was looking here:http://www.peope.net/old/regex.html
This never goes inside the if statement.
|
In order to use the+metacharacter, you need to tellregcomp()that you're using theextended POSIX syntax:
```
int reti = regcomp(®ex, e, REG_EXTENDED);
```
There are several other problems with this code, though, including castingconst char*tochar*, and ignoring the return value ofregcomp().
|
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
I'm really new to programming so please help me.
Here's my algorithm:
```
Enter a number
If the number is greater than 26
Subtract 26 from the number
Until the number is less than 26
Then display the final result
```
How do I write the code for this?
Thank You!
|
Try this. But next time do put some effort when formulating your question
```
if (scanf("%d", &n) == 1) {
while (n >= 26) {
n -= 26;
}
printf("%d", n) ;
}
```
|
In school we use the integer -999 to stopscanfand end the inputs that user put in the array.
For example:
```
while(input != -999) {
scanf("%i", &input)
userArray[i] = input;
i++;
}
```
I'm thinking about asking the user for string input and converting the input to an integer (usingatoiin stdlib) as long as the input is not 'stop'.
Would this be a good idea? Is there a better way to do this?
|
Reading in as a string and converting it to anintis actually preferable, as it avoids the potential pitfalls associated with the peculiarities ofscanf
Instead usefgets, which reads a line of input. This function adds the newline character to the input string, so be sure to trim that off before you do anything else. Once you've done that, you can usestrcmpto see if the string is equal to "stop", and if not then callatoi, or better yetstrtol(which has better error checking) to get the numerical value.
|
How can I remove opened file in linux?
In shell I can do this:
```
rm -rf /path/to/file_or_directory
```
But how can I do it in C?
I don't want to usingsystem()function.
I have seen unlink and remove method but it's haven't any flags to set force deletion.
|
Theunlinkandremovefunctions force deletion. Thermcommand is doing extra checksbeforeit calls one of those functions. But once you answery, it just uses that function to do the real work.
|
I can't figure out what exactly is the difference between the two following implementations:
```
char str[20] = "Hello World";
_strnset(str, '*', 5);
```
and
```
char str[20] = "Hello World";
memset(str, '*', 5);
```
They both produce the following outcome:
Output: ***** World!
Is there a preference between them?
|
_strnsetknows it's working with a string, so will respect the null terminator.memsetdoes not, so it won't.
As for preference,
memsetis in both the C and C++ standards,_strnsetis in neither.if available,_strnsetcan save you from buffer overflows if you write buggy code.
If you know you'll stay on Windows, use_strnset. Elsememset.
|
This question already has answers here:C function syntax, parameter types declared after parameter list(7 answers)Closed8 years ago.
I know that in C/C++ you declare function arguments like this:
```
type functionName(type arg1,type arg2 )
{
...code...
}
```
However there are a few places, for example herehttp://www.enderunix.org/docs/eng/daemon.phpWhere I see that a function can also be declared like this
```
type functionName(arg1, arg2)
type arg1;
type arg2;
{
...code..
}
```
Is that a valid declaration?
I've never seen anything like that in any C/C++ manual, can anyone tell me if this is correct, what are the pros and cons for this type of declaration if it is valid, and if possible point me to some manual or document that explains this.
Thanks
|
This is old style K&R C. Not sure it will work for C++.
|
This question already has answers here:Are typedef and #define the same in c?(11 answers)Closed8 years ago.
Aretypedef's handled by C's preprocessor?
That is, istypedef int foo_t;the same as#define foo_t int?
|
No, because that type of replacement won't work with more complex types. For instance:
```
typedef int tenInts[10];
tenInts myIntArray;
```
The declaration ofmyIntArrayis equivalent to:
```
int myIntArray[10];
```
To do this as a macro you'd have to make it a function-style, so it can insert the variable name in the middle of the expansion.
```
#define tenInts(var) int var[10]
```
and use it like:
```
tenInts(myIntArray);
```
This also wouldn't work for declaring multiple variables. You'd have to write
```
tenInts(myArray1);
tenints(myArray2);
```
You can't write
```
tenInts myArray1, myArray2;
```
like you can with atypedef.
|
I am trying to pass the address of one pointer to another pointer using the code below:
```
#include <stdio.h>
int main() {
int a = 45;
int *int_ptr = &a;
char *char_ptr;
*char_ptr = *int_ptr;
printf("char: %c", *char_ptr);
return 0;
}
```
I compile the code and when I try to run the the program, I get this error:34432 segmentation fault
How can I fix that?
Thanks
|
*char_ptr = *int_ptr;
Here you don't copy the pointer but you copy the content to whichint_ptris pointing to the area wherechar_ptris pointing. Sincechar* char_ptris not initialized, you get the segmentation fault.
What you probably meant to write is
```
char_ptr = (char *)int_ptr;
```
instead of
```
*char_ptr = *int_ptr;
```
|
I would like to count the characters from files using C.
I am curious if I open file usingopen()instead offopen(), is there any functions I can use to count any characters?open()takes arguments, the first of which is a char array.
Assume iffopen()is not used thenfscanf()is not used.
I am new to C. Just curious how it can work.
|
If you are working on a POSIX.1-2001 compatible system you can usestatorfstatwhich return astruct statwhich has a fieldst_sizefor the size in bytes. In POSIX 1 char = 1 byte = 8 bits.
If your system doesn't conform to POSIX.1 you can useopenand repeatedreads to find the size.
|
In school we use the integer -999 to stopscanfand end the inputs that user put in the array.
For example:
```
while(input != -999) {
scanf("%i", &input)
userArray[i] = input;
i++;
}
```
I'm thinking about asking the user for string input and converting the input to an integer (usingatoiin stdlib) as long as the input is not 'stop'.
Would this be a good idea? Is there a better way to do this?
|
Reading in as a string and converting it to anintis actually preferable, as it avoids the potential pitfalls associated with the peculiarities ofscanf
Instead usefgets, which reads a line of input. This function adds the newline character to the input string, so be sure to trim that off before you do anything else. Once you've done that, you can usestrcmpto see if the string is equal to "stop", and if not then callatoi, or better yetstrtol(which has better error checking) to get the numerical value.
|
How can I remove opened file in linux?
In shell I can do this:
```
rm -rf /path/to/file_or_directory
```
But how can I do it in C?
I don't want to usingsystem()function.
I have seen unlink and remove method but it's haven't any flags to set force deletion.
|
Theunlinkandremovefunctions force deletion. Thermcommand is doing extra checksbeforeit calls one of those functions. But once you answery, it just uses that function to do the real work.
|
I can't figure out what exactly is the difference between the two following implementations:
```
char str[20] = "Hello World";
_strnset(str, '*', 5);
```
and
```
char str[20] = "Hello World";
memset(str, '*', 5);
```
They both produce the following outcome:
Output: ***** World!
Is there a preference between them?
|
_strnsetknows it's working with a string, so will respect the null terminator.memsetdoes not, so it won't.
As for preference,
memsetis in both the C and C++ standards,_strnsetis in neither.if available,_strnsetcan save you from buffer overflows if you write buggy code.
If you know you'll stay on Windows, use_strnset. Elsememset.
|
This question already has answers here:C function syntax, parameter types declared after parameter list(7 answers)Closed8 years ago.
I know that in C/C++ you declare function arguments like this:
```
type functionName(type arg1,type arg2 )
{
...code...
}
```
However there are a few places, for example herehttp://www.enderunix.org/docs/eng/daemon.phpWhere I see that a function can also be declared like this
```
type functionName(arg1, arg2)
type arg1;
type arg2;
{
...code..
}
```
Is that a valid declaration?
I've never seen anything like that in any C/C++ manual, can anyone tell me if this is correct, what are the pros and cons for this type of declaration if it is valid, and if possible point me to some manual or document that explains this.
Thanks
|
This is old style K&R C. Not sure it will work for C++.
|
This question already has answers here:Are typedef and #define the same in c?(11 answers)Closed8 years ago.
Aretypedef's handled by C's preprocessor?
That is, istypedef int foo_t;the same as#define foo_t int?
|
No, because that type of replacement won't work with more complex types. For instance:
```
typedef int tenInts[10];
tenInts myIntArray;
```
The declaration ofmyIntArrayis equivalent to:
```
int myIntArray[10];
```
To do this as a macro you'd have to make it a function-style, so it can insert the variable name in the middle of the expansion.
```
#define tenInts(var) int var[10]
```
and use it like:
```
tenInts(myIntArray);
```
This also wouldn't work for declaring multiple variables. You'd have to write
```
tenInts(myArray1);
tenints(myArray2);
```
You can't write
```
tenInts myArray1, myArray2;
```
like you can with atypedef.
|
When I execute several different compilation commands via a makefile on one specific sourcecode (c-code). Is there a way to add these compilation commands as a comment to the source code for documentation reason?
|
You can do it by adding a preprocessor macro defined as a string containing the compiler flags, and then use this macro in an assignment to a constant string pointer.
Something like this in the Makefile
```
$(CC) $(CFLAGS) -DCFLAGS="$(CFLAGS)" ...
```
And in one source file do e.g.
```
const char cflags[] = CFLAGS;
```
There is no generic way to get it as a part of a comment though.
You could have a special marker in a comment block in a source file, and replace that using e.g.sedin a POSIX enviromnent (like Linux or OSX).
Something like this:
```
sed -i.bak -e 's@// CFLAGS: .*$@// CFLAGS: $(CFLAGS)@' some_source_file.c
```
|
```
typedef char line_t[MAX_INPUT + 1];
struct {
line_t line;
double score;
int linenumber;
} line_rank;
struct line_rank lines[MAX_LINES + 1];
```
Produces this :error: array type has incomplete element typewhich refers to the last line in the code I have provided.
I have looked everywhere and can't seem to find another question relating to structs manipulated in such a way.
|
You may want to addtypedefand deletestruct.
```
typedef char line_t[MAX_INPUT + 1];
typedef struct {
line_t line;
double score;
int linenumber;
} line_rank;
line_rank lines[MAX_LINES + 1];
```
|
Here is my code, how can I freenew_double_sizeafter it is called. I am a beginner in C, so thanks for help.
```
size_t get_doubled_size(Vector *vtr, size_t new_size){
size_t *new_double_size = malloc(sizeof(size_t));
*new_double_size = vtr -> capacity;
while(new_size > *new_double_size){
*new_double_size *= 2;
}
return *new_double_size;
}
```
and in another place, i call this like:
```
int doubled_size = get_doubled_size(....);
```
|
Clearly, you need to get its value before freeing it, e.g.:
```
size_t return_value = *new_double_size;
free(new_double_size);
return return_value;
```
But in this case, you don't even need to allocate space for the new size... just use asize_tvariable directly.
|
I am trying to convert thestart_timeof the linux kerneltask_structinto nanoseconds. I need to give it the argument ofconst struct timespec *butstart_timeis of typestruct timespec.
How would I make it a constant and a pointer to thetimespecstruct? Example code:
```
(*kinfo).start_time = timespec_to_ns((*current).start_time);
```
|
I would recommend picking up a primer on C, since you'll need to be very familiar with C programming (especially since the Linux kernel uses all the C trickery in the book) in order to write kernel code (or modify existing kernel code). However, to answer your question, you'll want to pass a pointer to the value (which is done using the&operator in C). Also, please use the correct dereferencing syntax for pointers to structures (p->attr).
```
kinfo->start_time = timespec_to_ns(¤t->start_time);
```
|
I have various kinds of printf macros in my code defined along those lines:
```
#define DEBUG(...) printf(__VA_ARGS__)
```
This works well:
```
DEBUG("Hello %d",1);
```
will be the same as
```
printf("Hello %d",1);
```
Now can I make my macro also edit the args that are passed in to, say, add a \n at the end of the first argument? I.e. so that
```
DEBUG("Hello %d",1);
```
turns into
```
printf("Hello %d\n",1);
```
|
I suggest using:
```
#define DEBUG(fmt, ...) printf(fmt "\n", __VA_ARGS__)
```
The drawback is that you have to have at least one non-format string argument, i.e. you cannot use the macro as:
```
DEBUG("foo");
```
anymore.
For some compilers there are work-arounds allowing empty__VA_ARGS__like
```
#define DEBUG(fmt, ...) printf(fmt "\n", ##__VA_ARGS__)
```
in gcc (thanks to M. Oehm).
|
In SDL2 -- is there a good way to detect a tablet versus phone or determine the screen size (physical screen size --- inches/cm/etc.)?
I want to detect small screens and enlarge button sizes.
I'm looking for the SDL2 way of doing this, preferably, since it doesn't matter whether the device is Android/iPhone/etc.
|
See this SDL2 function:https://wiki.libsdl.org/SDL_GetDisplayDPI
By getting the resolution and getting the physical DPI, you can get the screen size in inches.
Your specific question is discussed on their bug tracker here:
https://bugzilla.libsdl.org/show_bug.cgi?id=2473
There are some older SO questions that came up empty handed:iOS get physical screen size programmatically?
|
I'm using Yosemite. Just upgraded Xcode 7 and command line
I'm getting this error when cross-compile C project for iOS.
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/ar: No such file or directory
|
Xcode 7.0appears to have changed the default location for these tools:
```
nm
size
libtool
pagestuff
ar
codesign_allocate
dsymutil
install_name_tool
ld
ctf_insert
as
otool
strings
strip
redo_prebinding
lipo
nmedit
```
Toolchain Location:
```
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/
```
It may not include all command line tools by default, so you can also try downloading them:
Command Line Tools OS X 10.10 for Xcode 7
The only tools now in the former location are:
```
texturetool
csent
unwinddump
dyldinfo
dsymutil-classic
rebase
pngcrush
dwarfdump
PackageApplication
iphoneos-optimize
```
|
I have come across following definition in an embedded C source file:
```
const preamble_t OAD_Preamble @ ".preamble" =
{
HAL_OAD_RC_MAX, // Default program length of max if not using post-processing tool.
OAD_MANUFACTURER_ID, // Manufacturer ID
OAD_TYPE_ID, // Image Type
0x00000001 // Image Version
};
```
I have no idea about the @ part, can you please help me with this?
Edit:
This is in IAR compiler, used with TI SoCs.
|
This is the way you can specify a memory address or a section in which you would like to place your variable.
".preamble"is the name of a section,OAD_Preambleis the variable to be placed there.
You can also specify physical address after the at@sign:
```
const unsigned char port_bit @ 0x1800 = BIT0;
```
More information is inthis document.
Note:this is a non-portable compiler extension, not a part of the standard C syntax.
|
```
#include <iostream>
#include <cstdio>
using namespace std;
int max_of_four(int a, int b, int c, int d)
{
return( max((a,b),max(c,d)));
}
int main()
{
int a, b, c, d;
scanf("%d %d %d %d", &a, &b, &c, &d);
int ans = max_of_four(a, b, c, d);
printf("%d", ans);
return 0;
}
```
I ran this code on hackerRank. This code is doing fine for other testcases
except for:
17 13 3 15
for which it outputs : 15
I also tried to run the max(a,b) for 17 13
for which it righteously outputs 17.
Please Help!
|
You've forgotten to putmaxhere
```
return(max((a,b),max(c,d)));
```
It should bereturn( max(max(a,b),max(c,d)));
By the way, you really don't need the parentheses afterreturnas they're just making the code heavier and result in too many parentheses.
|
I've created a virtual filesystem that presents its outputs as read-only named pipes (i.e.,S_IFIFO).
As far asgetattris concerned, my host is showing that the permission mode is set correctly. However, when I attempt to open the pipe (e.g.,cat my_fuse_mount/my_pipe), it apparently does so but no data flows.
I was expecting theopen-read-releasesequence to do the necessary to open and push data into a named pipe, but apparently not. When I run in debugging mode, FUSE's log doesn't seem to indicate that it's trying to do anything.
What FUSE operation/s is/are used to push data into a named pipe?
|
FUSE can create special files such as named pipes, but its read and write operations are only operational for normal files. If you want to implement a pipe, you would need something likeCUSE.
|
I am new to C language and am wondering:
Why can't C functions return an array type?
I know that an array name is an address to the first value of the array, and arrays are second-class citizens in C.
|
You answered the question yourself already: arrays are second-class citizens.
C returns by value. Arrays cannot be passed by value, therefore they cannot be returned.
As to why arrays cannot be passed by value: this was a design decision made by K&R when they were first designing the language, and it's too late to change it now because all the existing C code would break.
|
So I have a text file that I'm using in the same directory as my C program and I'm using MinGW as the compiler. This is my input:
```
./program "hello" > helloworld.txt
```
In my program in the main function, I have:
```
#include <stdio.h>
int main(int argc, char *argv[]) {
char c;
while ((c=getchar()) != EOF) {
printf("test\n");
}
return 0;
}
```
Nothing is printing. The text file definitely has lines in it. I don't know what's going on. This assignment voids the use of fopen() and all that. It is getchar() and stdin only.
|
Your command isn't reading from the text file, it's writing to it. If you want to read from it, you need to do this:
```
./program < helloworld.txt
```
helloworld.txt:
```
this
is a
test
```
Output:
```
test
test
test
test
test
test
test
test
test
test
test
test
test
test
test
```
|
Given:
```
int a = 1;
int *p = &a;
int b = -1;
*++p = 2;
```
Is there anything that prevents b from being over written from -1 to 2 if in the apparently not unlikely event the two a and b were written next to each other in memory?
|
How does C protect pointer memory?
It doesn't.
Is there anything that prevents b from being over written from -1 to 2
if in the unlikely event the two a and b were written next to each
other in memory?
No.
And the two variables being "next to each other in memory" isn't unlikely at all.
C give you the power to cause a lot of problems it you're not careful.
|
I have a question:
Is it possible to executesendtoto send information from one process which is initialized on UDP to another process initialized on TCP (this is all in the same.c)?.
I have one process which receives information on UDP and this one has to send this information locally to the TCP one and I don't know how to connect (I know you cannot connect with UDP, I mean just send the datagram) them.
Can anyone help me?
Thank you.
|
The process that is receiving UDP packets has to open a separate TCP socket to send to the other process.
So at startup this process should first open up a UDP socket to receive datagrams. Then it gets a TCP socket and uses that to connect to the other process using theconnectfunction. Then, whenever data comes in on the UDP socket, you take that data and send it out usingsendover the TCP socket for the other server to read.
|
I have installed and configured doxygen for openvpn source code, but I am unable to get the call graphs and diagrams of it. I only get config-msvc.h and config.h files in the file list of code documentation.
Can anybody tell me how to configure doxygen to produces these call and caller trees for openvpn source code ? I do have graphviz installed.
|
Open your doxygen file (ex- project_name.doxygen).In that you will see one option likeDiagrams to Generate.In that select all check boxes under last option namedUse Dot tool from the graphViz package to generate.And if there are many directoris in your project you need to add that directory path in Input Directories.I am attaching image, hope this will help you.
|
I am new to C language and am wondering:
Why can't C functions return an array type?
I know that an array name is an address to the first value of the array, and arrays are second-class citizens in C.
|
You answered the question yourself already: arrays are second-class citizens.
C returns by value. Arrays cannot be passed by value, therefore they cannot be returned.
As to why arrays cannot be passed by value: this was a design decision made by K&R when they were first designing the language, and it's too late to change it now because all the existing C code would break.
|
So I have a text file that I'm using in the same directory as my C program and I'm using MinGW as the compiler. This is my input:
```
./program "hello" > helloworld.txt
```
In my program in the main function, I have:
```
#include <stdio.h>
int main(int argc, char *argv[]) {
char c;
while ((c=getchar()) != EOF) {
printf("test\n");
}
return 0;
}
```
Nothing is printing. The text file definitely has lines in it. I don't know what's going on. This assignment voids the use of fopen() and all that. It is getchar() and stdin only.
|
Your command isn't reading from the text file, it's writing to it. If you want to read from it, you need to do this:
```
./program < helloworld.txt
```
helloworld.txt:
```
this
is a
test
```
Output:
```
test
test
test
test
test
test
test
test
test
test
test
test
test
test
test
```
|
I want to be able to set a min/max range and use it to check valid/invalid inputs while reading values from a file.
My min and max values in the first line are1and10, respectively. This is my text file to be tested (num.txt):
```
1 10
2
4
5
```
In this program, I want to usefscanf(stdin , ...):
```
fscanf( stdin, "%d%c", &num, &c );
```
How can I read the first line and check it for the min and max values and then continue reading the following lines?
|
To read from a file you can do this -
```
FILE *fp;
fp=fopen("num.txt","r"); // check its return .
fscanf(fp,"%d %d",&min,&max);
```
To keep reading further values you can usefscanfin a loop-
```
while(fscanf(fp,"%d",&variable)==1){ // on success fscanf return 1 here, till fscanf is successful loop will iterate
// do you operations
}
```
|
I came across a piece of code that reads:
```
++myStruct->counter
```
I'm confused on how the ++ operator and -> operator are evaluated here. The ++ has precedence over the -> operator and left to right evaluation. It appears the ++ operator would actually perform pointer arithmetic on 'myStruct', not increment the counter member.
|
The ++ has precedence over the -> operator and left to right evaluation.
This is not correct - postfix operators like->have higher precedence than unary (prefix) operators++and--. The expression is parsed as
```
++(myStruct->counter)
```
so thecountermember ofmyStructis being incremented.
|
Signal function return the value of old handler , but what is the situation where old handler value may useful, because most of the places we don't check return value of signal function.
|
There are two situations when the value of the old handler is useful:
You want to implement a new handler that calls the old handler at some point during its run, orYou want to replace an old handler with a new one, and put the old one back at some point.
In both cases you store the old handler returned by the replacement function.
|
The latest assignment in my Operating Systems class required us to create a subdirectory(named tmpFolder) using the mkdir command, with no context whatsoever. The code I currently have is based off of the Minix3 appendix and the manual for mkdir My professor isn't the most helpful and the rest of the class is also having trouble with it so I figured I'd ask about it here.
Here is my relevant code:
```
#include <sys/stat.h>
{
int tmpFolder;
tmpFolder = mkdir(tmpFolder, 0777);
}
```
Can someone please explain to me why that is wrong because it is very frustrating having the professor not explaining why I'm wrong
|
mkdir's first argument is the path you want to create. You're providing tmpFolder which is an int. Something like this would make more sense:
```
int status;
status = mkdir("/tmp/subdir", 0777)
```
|
I have a requirement to have an unsigned 3 byte type in C. I am looking for a way to pack them into a single unsigned int.
Is this safe or does this need to be stored inside an array/structure for the 24 bit size?
```
unsigned int pack_3Byte(unsigned char b1, unsigned char b2, unsigned char b3)
{
return (b1 << 16) | (b2 << 8) | (b3);
}
```
|
Your code is correct but like Olaf says you should use the types uint8_t and uint32_t to ensure that your types are really the width you expect them to be.
This may not be a problem right now, but you should also be aware that the bytes in an integer are stored in different order on different processors. This is calledendianness.
|
I wish to print a pattern in C language like this:
```
2
2 3
3 4 5
4 5 6 7
5 6 7 8 9
```
Currently I have this:
```
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
if(i>=j)
{
printf(" %d ",j+i-1);
}
}
printf("\n");
}
printf("\n");
}
```
And output is:
```
1
2 3
3 4 5
4 5 6 7
5 6 7 8 9
```
How do I make it to start with2, then2 3and so on?? Please help.
Thanks in advance!!
|
```
int main()
{
int i = 2;
int shift = 0;
printf("2\n");
for(int len = 2; len < 6; len++){
for(int j = i; j < i + len; j++){
printf("%d\t", j+shift);
}
printf("\n");
shift++;
}
}
```
|
please i can't understand the while loop , why the loop show A two time and not one
```
char *s,*t;
s="ABC";
t="AA";
do {printf("A");}
while(*s++==*t++);
printf("%d %d",*s-*t);
```
|
In your code
```
printf("%d %d",*s-*t);
```
invokes undefined behavior as you're not supplying enough argument to sate the supplied format specifiers.
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed8 years ago.Improve this question
I am trying to understand memory pool concept in C. I understand memory pool is a pre-allocated memory space with a fixed size. But I want know is there any standard Library or API that can help to implement memory pool in C ?
I Don't want to implement memory pool my self in C , I am in search of someSTANDARD API or LIB for my C program that can do memory pool operation.
|
Windows API offers that you can create your own heap (block of virtual memory):
HeapCreate. Then you useHeapAllocandHeapFreewithin that.
|
Can anyone report experiences with that HWUT tool (http://hwut.sourceforge.net)?Has anyone had experiences for some longer time?What about robustness?Are the features like test generation, state machine walking, and Makefile generation useful?What about execution speed? Any experience in larger projects?How well does code coverage measurments perform?
|
I have been using HWUT since several years for software unit testing for larger automotive infotainment projects. It is easy to use, performance is great and it does indeed cover state machine walkers, test generation and make-file generation, too. Code coverage is working well. What I really like about HWUT are the state machine walker and test generation, since they allow to create a large amount test cases in very short time. I highly recommend HWUT.
|
I'm looking at the legacy C project which relies on GNU Autotools. The existing M4 script (incorrectly) checks forFreeTypeheaders like this:
```
AC_CHECK_HEADERS(freetype.h)
```
which is not the wayFreeTypeshould be included. The right way is:
```
#include <ft2build.h>
#include FT_FREETYPE_H
```
How do I require thatallheaders are included in the test program, noteitherof them?
|
To check for multiple headers depending on each other, you can use AC_COMPILE_IFELSE
Also if you google for "freetype m4" you will find several macros how to detect freetype.
|
In java people say inputstream reads a file byte by byte then using buffered reader they change to characterstream.But in C char refer to byte(8 bit).Then what we call as character and byte in java.
|
In Java abyteis a signed 8-bit value, and acharis an unsigned 16-bit value. TheCharacteris both a wrapper type forcharand a utility class for a number of useful method supportingchar
The key difference between an InputSTream is that it reads binary data, one byte at a time. AReaderis for reading text and it decodes bytes intocharusing the character encoding you set or the default encoding e.g.UTF-8can turn 1, 2 or 3 bytes into a singlechar.
I suggest you learn more about the very basics of Java. It will save you a lot of time with these sort of questions.
|
I am using the source file fromhttps://github.com/contiki-os/contikiI added a new directory (say/foo) that includes some .c and .h files
I need to use them onexamples/cc26xx, although I included the .h files (under/foo) to cc26xx-demo.c, it doesn't really include the files when I runmake
can anyone tell me how do I need to include them either onexamples/cc26xx/MakefileorMakefile.include
|
addingPROJECT_SOURCEFILES += mylib.cto Makefile solved the issue.
|
What is the correct way to create a new instance of a struct? Given the struct:
```
struct listitem {
int val;
char * def;
struct listitem * next;
};
```
I've seen two ways..
The first way (xCode says this is redefining the struct and wrong):
```
struct listitem* newItem = malloc(sizeof(struct listitem));
```
The second way:
```
listitem* newItem = malloc(sizeof(listitem));
```
Alternatively, is there another way?
|
It depends if you want a pointer or not.
It's better to call your structure like this :
```
typedef struct s_data
{
int a;
char *b;
// etc..
} t_data;
```
After to instanciate it for a no-pointer structure :
```
t_data my_struct;
my_struct.a = 8;
```
And if you want a pointer you need to malloc it like that :
```
t_data *my_struct;
my_struct = malloc(sizeof(t_data));
my_struct->a = 8
```
I hope this answers your question.
|
If I run such a bash script, and in the script, it will invoke some executable command, such as the following
```
myexec args1 arg2 > out.txt
```
myexec will print some log info through the c API printf. If I interrupt the script, because myexec is stuck by some unknown reason, does some log information will be lost, and not save to the out.txt file? In my experiment, I found it is, but is there any way to solve this? and I do not know why the log information not flush to the out.txt file
========
I use the stdbuf solved my problem, the related question is:Force line-buffering of stdout when piping to tee
|
When you interrupt the script, there's a good chance thestdoutbuffer isn't flushed. In your program, immediately after everyprintf, add anfflush(stdout)to flush the buffer. Alternatively, add a newline character (\n) at the end of yourprintf- that flushes the buffer too (but adds a newline to your log output).
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed8 years ago.Improve this question
I am trying to understand memory pool concept in C. I understand memory pool is a pre-allocated memory space with a fixed size. But I want know is there any standard Library or API that can help to implement memory pool in C ?
I Don't want to implement memory pool my self in C , I am in search of someSTANDARD API or LIB for my C program that can do memory pool operation.
|
Windows API offers that you can create your own heap (block of virtual memory):
HeapCreate. Then you useHeapAllocandHeapFreewithin that.
|
Can anyone report experiences with that HWUT tool (http://hwut.sourceforge.net)?Has anyone had experiences for some longer time?What about robustness?Are the features like test generation, state machine walking, and Makefile generation useful?What about execution speed? Any experience in larger projects?How well does code coverage measurments perform?
|
I have been using HWUT since several years for software unit testing for larger automotive infotainment projects. It is easy to use, performance is great and it does indeed cover state machine walkers, test generation and make-file generation, too. Code coverage is working well. What I really like about HWUT are the state machine walker and test generation, since they allow to create a large amount test cases in very short time. I highly recommend HWUT.
|
I'm looking at the legacy C project which relies on GNU Autotools. The existing M4 script (incorrectly) checks forFreeTypeheaders like this:
```
AC_CHECK_HEADERS(freetype.h)
```
which is not the wayFreeTypeshould be included. The right way is:
```
#include <ft2build.h>
#include FT_FREETYPE_H
```
How do I require thatallheaders are included in the test program, noteitherof them?
|
To check for multiple headers depending on each other, you can use AC_COMPILE_IFELSE
Also if you google for "freetype m4" you will find several macros how to detect freetype.
|
In java people say inputstream reads a file byte by byte then using buffered reader they change to characterstream.But in C char refer to byte(8 bit).Then what we call as character and byte in java.
|
In Java abyteis a signed 8-bit value, and acharis an unsigned 16-bit value. TheCharacteris both a wrapper type forcharand a utility class for a number of useful method supportingchar
The key difference between an InputSTream is that it reads binary data, one byte at a time. AReaderis for reading text and it decodes bytes intocharusing the character encoding you set or the default encoding e.g.UTF-8can turn 1, 2 or 3 bytes into a singlechar.
I suggest you learn more about the very basics of Java. It will save you a lot of time with these sort of questions.
|
I am using the source file fromhttps://github.com/contiki-os/contikiI added a new directory (say/foo) that includes some .c and .h files
I need to use them onexamples/cc26xx, although I included the .h files (under/foo) to cc26xx-demo.c, it doesn't really include the files when I runmake
can anyone tell me how do I need to include them either onexamples/cc26xx/MakefileorMakefile.include
|
addingPROJECT_SOURCEFILES += mylib.cto Makefile solved the issue.
|
What is the correct way to create a new instance of a struct? Given the struct:
```
struct listitem {
int val;
char * def;
struct listitem * next;
};
```
I've seen two ways..
The first way (xCode says this is redefining the struct and wrong):
```
struct listitem* newItem = malloc(sizeof(struct listitem));
```
The second way:
```
listitem* newItem = malloc(sizeof(listitem));
```
Alternatively, is there another way?
|
It depends if you want a pointer or not.
It's better to call your structure like this :
```
typedef struct s_data
{
int a;
char *b;
// etc..
} t_data;
```
After to instanciate it for a no-pointer structure :
```
t_data my_struct;
my_struct.a = 8;
```
And if you want a pointer you need to malloc it like that :
```
t_data *my_struct;
my_struct = malloc(sizeof(t_data));
my_struct->a = 8
```
I hope this answers your question.
|
If I run such a bash script, and in the script, it will invoke some executable command, such as the following
```
myexec args1 arg2 > out.txt
```
myexec will print some log info through the c API printf. If I interrupt the script, because myexec is stuck by some unknown reason, does some log information will be lost, and not save to the out.txt file? In my experiment, I found it is, but is there any way to solve this? and I do not know why the log information not flush to the out.txt file
========
I use the stdbuf solved my problem, the related question is:Force line-buffering of stdout when piping to tee
|
When you interrupt the script, there's a good chance thestdoutbuffer isn't flushed. In your program, immediately after everyprintf, add anfflush(stdout)to flush the buffer. Alternatively, add a newline character (\n) at the end of yourprintf- that flushes the buffer too (but adds a newline to your log output).
|
I am unsure why I am receiving a segmentation fault when my program hits the firstifstatement.
This is a method in a simpleShell program that's sole purpose is parsing stdin input stored incmdand parse by whitespace into separate arguments inargs
It will never print theifstatement
```
void parseCmd(char* cmd, char** args)
{
int i;
printf("----------> Parsed here \n");
for(i = 0; i < MAX_LINE; i++) {
args[i] = strsep(&cmd, " ");
if (args[i][0] == '-') {
printf("I was here... \n");
}
if(args[i] == NULL) break;
}
}
```
|
You're missing two obvious NULL checks.
Check for NULL againstargsCheck for NULL instrsep()return value.
Otherwise, you may very well attempt a NULL pointer deference in either case which results inundefined behavior.
|
Does NULL pointer take any memory?
If it takes memory,then how much memory is consumed by it and what is the significant use ofNULLpointer if it takes memory?
|
A pointervalue(NULLor not) requires some amount of space to store and represent (4 to 8 bytes on most modern desktop systems, but could be some oddball size depending on the architecture).
The pointer valueNULLrepresents a well-defined "nowhere"; it's aninvalidpointer value guaranteed to compare unequal to the address of any object or function in memory. The macroNULLis set to thenull pointer constant, which is a zero-valued integer expression (either a naked0, or(void *) 0, or some other expression that evaluates to0).
After the code has been compiled, the null pointer constant will be replaced with the appropriate null pointervaluefor that particular platform (which may be0x00000000, or0xFFFFFFFF, or0xDEADBEEF, or some other value).
|
I'm trying to write a basic simple tokenizer using C.
I have a problem in the algorithm and the string token doesn't point to the correct token.
Here is my implementation:
```
char *test="root/ahmed/tolba";
Tokenize(test, '/');
...
void Tokenize(char* String, char Split)
{
char *strings = String;
for (size_t i = 0, j = 0; String[i] != 0; i++)
{
if (String[i] == Split)
{
const char * token = &strings[j];
size_t length = i-j;
j=i+1;
printf(token);
}
}
}
```
|
It's hard to see what you're asking, but probably you want to print stringstokenwith lengthlength?
Use printf as follows:
```
printf("%.*s\n", length, token);
```
That syntax (%.*s) allows you to specify the amount to print.
|
I read the answers to the various questions on how to generate random numbers between 0 and 1.
float random = ((float) rand()) / (float) RAND_MAX;
Now I'm curious. Considering that the generator repeats the numbers (for a truly random number), how many iterations do you think makes it cover almost all possibilities.
I code in C and use the gcc compiler.
|
If it's atruerandom number generator (i.e. the probability of drawing a given number is1 / RAND_MAXand independent of the previous drawn set of numbers), then you'd need an infinite number of iterations to cover all possibilities.
rand()however will recover all iterations inRAND_MAXtrials if it's implemented as a linear congruential generator withperiodicityofRAND_MAX(as it frequently is).
|
If I have the following linked structured and each node has a hash table of its name as key and its value as its object. If I have a pointer to Node1, how would I go to Node 2, using the hashtable of Node 1 ?
Each node has a hash table of its name, and the node itself. but If I have a pointer to Node 1, how would I go to Node2 without using linked list structure, just using the hashtable.
```
struct Node
{
hashtable[node_name, Node];
};
```
If I haveNode *node1;How would I go to node_2; using its hashtable ?
|
If you have "node1", and want to find a child-node, then you need to find it in the has-table. Do do that, simply calculate the hash of the node you want to find, and check if it's in the table.
If the hash is in the table, you then have the wanted child-node, else there is no such child.
|
I have some source files.c; they are actually a library provided by others. When I build my program to use this library, I have to compile these files again. I can't to compile the files into a static library because the sources contain some preprocessor flags. I have to generate many static libraries with different composition of preprocessor flags.
So, is there any technique that I can build a static library, and select what preprocessor flags should be used when linking with this library?
|
No you can't. You would need the source code. There are three basic steps in c compiling to go from source to executable.
Source->Preprocessor->Compilation into Object Files->Linking->Executable
The static libraries are kind of like the object files. They have already been compiled and preprocessed before that. Static libraries are used by the linker to make the final executable.
|
What's wrong with this?
```
int main(int argc, char** argv) {
printf("%% ");
size_t len;
ssize_t read;
char* line;
int size;
read = getline(&line, &len,stdin);
printf("my name: %s\n",argv[0]);
printf("%s",line);
char* args[]= {"yoyoyo","hi","me",NULL};
return 0;
}
```
Debugging shows Exception: EXC_BAD_ACCESS (code=1, address=0xa66647360)) on the
printf("my name: %s\n",argv[0]);
line.
|
You're forgetting to initialize the values supplied togetline().
Try withchar *line = NULL;andsize_t len = 0;instead.
Theman 3 getlineman page has an example you could adapt.
|
I have some source files.c; they are actually a library provided by others. When I build my program to use this library, I have to compile these files again. I can't to compile the files into a static library because the sources contain some preprocessor flags. I have to generate many static libraries with different composition of preprocessor flags.
So, is there any technique that I can build a static library, and select what preprocessor flags should be used when linking with this library?
|
No you can't. You would need the source code. There are three basic steps in c compiling to go from source to executable.
Source->Preprocessor->Compilation into Object Files->Linking->Executable
The static libraries are kind of like the object files. They have already been compiled and preprocessed before that. Static libraries are used by the linker to make the final executable.
|
What's wrong with this?
```
int main(int argc, char** argv) {
printf("%% ");
size_t len;
ssize_t read;
char* line;
int size;
read = getline(&line, &len,stdin);
printf("my name: %s\n",argv[0]);
printf("%s",line);
char* args[]= {"yoyoyo","hi","me",NULL};
return 0;
}
```
Debugging shows Exception: EXC_BAD_ACCESS (code=1, address=0xa66647360)) on the
printf("my name: %s\n",argv[0]);
line.
|
You're forgetting to initialize the values supplied togetline().
Try withchar *line = NULL;andsize_t len = 0;instead.
Theman 3 getlineman page has an example you could adapt.
|
I have following code c++ code:
```
static void print_string(JNIEnv * env, jclass clazz, jstring str){
jboolean isCopy;
const char* utf_string;
utf_string = env->GetStringUTFChars(str, &isCopy);
env->ReleaseStringUTFChars(str, utf_string);
//LOGI("%s",utf_string);
// LOGE("JNI Out = %s", utf_string);
printf("jni out: %s",utf_string);
__android_log_print(ANDROID_LOG_INFO, "MyTag", "The value is %s", utf_string);
env->ReleaseStringUTFChars(str, utf_string);
}
```
I don't see any output in logcat. So where does it goes? How can I see it?
|
Accordint tothe docsthe output is lost:
By default, the Android system sendsstdoutandstderr(System.outandSystem.err) output to/dev/null.
There are methods to change that (on rooted devices), for example usingsetprop, taken from the docs:
```
$ adb shell stop
$ adb shell setprop log.redirect-stdio true
$ adb shell start
```
|
Is there a difference between those two variants of callingfreeafter allocating memory on the heap:
```
// variant 1
int* p1 = (int*) malloc(sizeof(int)*4);
free(p1);
//variant 2
int* p2 = (int*) malloc(sizeof(int)*4);
free(*p2);
*p2 = NULL;
```
|
Yes, there is a difference.
Variant 2 is invalid.freeexpects a pointer previously returned bymalloc,calloc, orrealloc.*p2is the firstintin the allocated space, though. Asman freesays, undefined behavior occurs therefore (quotation adjusted for this specific case):
free()function frees the memory space pointed to by [p1], which must have been returned by a previous call tomalloc(),calloc(), orrealloc(). Otherwise, [...] undefined behavior occurs.
Notes:
don't cast the result ofmalloc
|
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.Closed7 years ago.Improve this question
are there any C/C++ compilers which use 8bytes as the size of int data type?
```
printf("Size of int = %d bytes",sizeof(int));
```
Here the output should be :-
```
Size of int = 8 bytes
```
Please name such a compilerThank you
|
If you look at the section on 64 bit data models inthe Wikipedia entry for 64 bit computingyou will see that there are two models whereints are 64 bits,ILP64andSILP64. An example given for ILP64 is HAL Computer Systems port of Solaris to SPARC64, and for SILP64 "Classic"UNICOS. Obviously any compiler for either of these two systems would need to use 64 bitints, although they are both somewhat obscure.
Most common 64 bit environments areLP64of course, whereintis 32 bits.
|
How can I calculate the number of steps required to make a directed graph strongly connected by swapping edges? A step is an edge swap.
Note:Every node will have an in-degree of 1 and an out-degree of 1.
Eg->1->3,2->1,3->2and4->4isnotstrongly connected. Now, if we swap4->1and2->4then it becomes strongly connected.
|
Now, the solution goes like this:
First, calculatetotalnumber ofdisjoint cycles or loopsin the graph you havelet say the number of disjoint cycle or loops areN.PrintN-1, that would be your answer to this question. (N-1Why ?Think).
|
I have a simple program in C that I am using to learn how to use scanf() for future school projects. When I execute the program through the linux terminal I have to use the end command to end the program and then it will give me the value that I input. Is there something wrong with my code?
Problem: After scanf function is executed, the printf function afterward will not be executed until I use the end terminal command.
code
```
#include<stdio.h>
int main(void)
{
int a = 0;//declaring int a
printf("Type a value in: ");//asks for value
scanf("%d\n" , &a);//scans use input assigns value to a
printf("Your value is %d \n" , a);//prints value of a
return 0;//returns value to end program
}//end main
```
|
Get rid of the "\n" in the scanf format string.
SeeUsing "\n" in scanf() in C
|
I've seen an assignment similar to
```
*p = array[i];
```
in a code base and I'm wondering what effects this has on the pointer. If this has been asked before, I apologize but the search engine kept eating my special characters and may have hampered my search.
|
Your question is unclear because there is not enough details given.
As has been said in the comments*p = array[i]dereferencespand assigns the content of what's atarray[i]to whateverppoints to.
Example 1
```
int i = 0, j;
int *p = &j; // p is a pointer to integer and now it points to j
int array[2] = { 4, 2 };
*p = array[i]; // this means j = array[0] so j = 4 and j is 4 now
```
Example 2
```
int i = 0, *j, k, l;
int **p = &j; // p is a pointer to pointer to integer and now it points to j
int* array[2] = { &k, &l };
*p = array[i]; // this means j = array[0] so j = &k and j points now to k
```
|
I've seen an assignment similar to
```
*p = array[i];
```
in a code base and I'm wondering what effects this has on the pointer. If this has been asked before, I apologize but the search engine kept eating my special characters and may have hampered my search.
|
Your question is unclear because there is not enough details given.
As has been said in the comments*p = array[i]dereferencespand assigns the content of what's atarray[i]to whateverppoints to.
Example 1
```
int i = 0, j;
int *p = &j; // p is a pointer to integer and now it points to j
int array[2] = { 4, 2 };
*p = array[i]; // this means j = array[0] so j = 4 and j is 4 now
```
Example 2
```
int i = 0, *j, k, l;
int **p = &j; // p is a pointer to pointer to integer and now it points to j
int* array[2] = { &k, &l };
*p = array[i]; // this means j = array[0] so j = &k and j points now to k
```
|
Suppose I want to get the last element of an automatic array whose size is unknown. I know that I can make use of thesizeofoperator to get the size of the array and get the last element accordingly.
Is using*((*(&array + 1)) - 1)safe?
Like:
```
char array[SOME_SIZE] = { ... };
printf("Last element = %c", *((*(&array + 1)) - 1));
```
```
int array[SOME_SIZE] = { ... };
printf("Last element = %d", *((*(&array + 1)) - 1));
```
etc
|
No, it is not.
&arrayis of type pointer tochar[SOME_SIZE](in the first example given). This means&array + 1points to memory immediately past the end ofarray. Dereferencing that (as in(*(&array+1))gives undefined behaviour.
No need to analyse further. Once there is any part of an expression that gives undefined behaviour, the whole expression does.
|
Program:
```
#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
void main()
{
int fd=open("b.txt",O_RDONLY);
fchmod(fd,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH);
}
```
Output:
```
$ ls -l b.txt
----r----- 1 mohanraj mohanraj 0 Sep 12 15:09 b.txt
$ ./a.out
$ ls -l b.txt
----r----- 1 mohanraj mohanraj 0 Sep 12 15:09 b.txt
$
```
For the above program, My expected output is to set the permission for b.txt as "rw_rw_r__". But, It still remains in the old
permission. Why it will be like this. Is this code have any bug ?
|
You don't have permission to modify the file, call your program withsudoto have it succeed.
Also always check the return value of functions likeopenandfchmodand handle the errors .
|
I have a function in C:
```
void start_fun()
{
// do something
}
```
I want to usepthread_create()to create a thread and the start routine isstart_fun(), without modifingvoid start_fun(), how to get the function pointer tostart_fun();
|
If you write the function namestart_funwithout any parameters anywhere in your code, you will get a function pointer to that function.
Howeverpthread_create expects a function of the formatvoid* func (void*).
If rewriting the function isn't an option, you'll have to write a wrapper:
```
void* call_start_fun (void* dummy)
{
(void)dummy;
start_fun();
return 0;
}
```
then pass call_start_fun to pthread_create:
```
pthread_create(&thread, NULL, call_start_fun, NULL);
```
|
Static inline functions are greatly preferred over macros. They
provide type safety.
What does this mean? Can anybody explain and if possible provide an example?
|
This means that it's better to do (in a header):
```
static inline int max(int a, int b)
{
return a > b ? a : b;
}
```
than
```
#define MAX(a, b) ((a) > (b) ? (a) : (b))
```
Since the former has its parameters declared as beingint, along with the result
(so your C compiler would complain clearly if you codemax(3.14, "pi"), but if you used a macro, the error would be more cryptic or unnoticed)
Functions are at a higher level than macros, which are just dumb text replacement.
Since the function isstatic, it won't be visible outside the C file that#includes the header its in, so there won't be any "symbol re-defined" clashes when you link together several C files using this.
|
This might be a silly question. but I was wandering a long time searching for this .but couldn't solve. For some functions I've seen (8) also. They are mostly seen on documentations. Could anyone please help.
|
Often in the manualmanyou will see numbers after the functions to distinguish which section of the manual the page comes from.
You can viewmalloc(3)by typeingman 3 mallocon a unix style terminal with the appropriate man pages installed.
These are not specific to the C language.
|
In a function like this:
```
char nextchr (void* p)
{
((char*)p)++;
return *(((char*)p));
}
```
That is supposed to return the second character of a string literal passed as the argumentpsimply fails to do that.
Why that could be?
Solution summery:
@M.M :++requires a lvalue (left-handed value) for it to apply to and the result from the type-cast isn't that.
@OP Update :
Some compilers (generally /old C89/ /compilers/ like mine) may allow((char*)source)++;/as long as it is not passed as argument to a function/ even though it is illegal and proven as illegal by the C standards.
|
++requires an lvalue. Your code could be:
```
char *c = p;
++c;
return *c;
```
although it would be a lot simpler to writereturn ((char *)p)[1];
|
I have a function in C:
```
void start_fun()
{
// do something
}
```
I want to usepthread_create()to create a thread and the start routine isstart_fun(), without modifingvoid start_fun(), how to get the function pointer tostart_fun();
|
If you write the function namestart_funwithout any parameters anywhere in your code, you will get a function pointer to that function.
Howeverpthread_create expects a function of the formatvoid* func (void*).
If rewriting the function isn't an option, you'll have to write a wrapper:
```
void* call_start_fun (void* dummy)
{
(void)dummy;
start_fun();
return 0;
}
```
then pass call_start_fun to pthread_create:
```
pthread_create(&thread, NULL, call_start_fun, NULL);
```
|
Static inline functions are greatly preferred over macros. They
provide type safety.
What does this mean? Can anybody explain and if possible provide an example?
|
This means that it's better to do (in a header):
```
static inline int max(int a, int b)
{
return a > b ? a : b;
}
```
than
```
#define MAX(a, b) ((a) > (b) ? (a) : (b))
```
Since the former has its parameters declared as beingint, along with the result
(so your C compiler would complain clearly if you codemax(3.14, "pi"), but if you used a macro, the error would be more cryptic or unnoticed)
Functions are at a higher level than macros, which are just dumb text replacement.
Since the function isstatic, it won't be visible outside the C file that#includes the header its in, so there won't be any "symbol re-defined" clashes when you link together several C files using this.
|
This might be a silly question. but I was wandering a long time searching for this .but couldn't solve. For some functions I've seen (8) also. They are mostly seen on documentations. Could anyone please help.
|
Often in the manualmanyou will see numbers after the functions to distinguish which section of the manual the page comes from.
You can viewmalloc(3)by typeingman 3 mallocon a unix style terminal with the appropriate man pages installed.
These are not specific to the C language.
|
In a function like this:
```
char nextchr (void* p)
{
((char*)p)++;
return *(((char*)p));
}
```
That is supposed to return the second character of a string literal passed as the argumentpsimply fails to do that.
Why that could be?
Solution summery:
@M.M :++requires a lvalue (left-handed value) for it to apply to and the result from the type-cast isn't that.
@OP Update :
Some compilers (generally /old C89/ /compilers/ like mine) may allow((char*)source)++;/as long as it is not passed as argument to a function/ even though it is illegal and proven as illegal by the C standards.
|
++requires an lvalue. Your code could be:
```
char *c = p;
++c;
return *c;
```
although it would be a lot simpler to writereturn ((char *)p)[1];
|
This might be a silly question. but I was wandering a long time searching for this .but couldn't solve. For some functions I've seen (8) also. They are mostly seen on documentations. Could anyone please help.
|
Often in the manualmanyou will see numbers after the functions to distinguish which section of the manual the page comes from.
You can viewmalloc(3)by typeingman 3 mallocon a unix style terminal with the appropriate man pages installed.
These are not specific to the C language.
|
In a function like this:
```
char nextchr (void* p)
{
((char*)p)++;
return *(((char*)p));
}
```
That is supposed to return the second character of a string literal passed as the argumentpsimply fails to do that.
Why that could be?
Solution summery:
@M.M :++requires a lvalue (left-handed value) for it to apply to and the result from the type-cast isn't that.
@OP Update :
Some compilers (generally /old C89/ /compilers/ like mine) may allow((char*)source)++;/as long as it is not passed as argument to a function/ even though it is illegal and proven as illegal by the C standards.
|
++requires an lvalue. Your code could be:
```
char *c = p;
++c;
return *c;
```
although it would be a lot simpler to writereturn ((char *)p)[1];
|
I'm building a simple C program, which takes a user input parameter (URL) usingscanf(), as the code below reflects. I'm now looking for the best "standard" way to read/write the remote file to a local file... which I will then preform a grep (search) operation on the new local source file.
//CODE
```
#include <stdio.h>
int main(void){
char url[255];
//USER INPUT URL
printf("ENTER URL: ");
scanf("%s", &url);
//GET FILE AT URL(REMOTE) AND COPY TO (LOCAL)
//RETURN
return 0;
}
```
|
You could use libcurl, or just shell out and usewgetorcurl, honestly.
```
char command[1024];
snprintf(command, 1024, "wget -c '%s'", url);
system(command); // add error handling
```
That will take considerably less effort.
|
I am getting a warning when I iterate through the character pointer and check when the pointer reaches the null terminator.
```
const char* message = "hi";
//I then loop through the message and I get an error in the below if statement.
if (*message == "\0") {
...//do something
}
```
The error I am getting is:
```
warning: comparison between pointer and integer
('int' and 'char *')
```
I thought that the*in front ofmessagedereferences message, so I get the value of where message points to? I do not want to use the library functionstrcmpby the way.
|
It should be
```
if (*message == '\0')
```
In C, simple quotes delimit a single character whereas double quotes are for strings.
|
I'm a beginner at C and can't find the answer to this anywhere because I don't know how to word it so I'm just going to ask a question.
I understand basic looping but what I want to do is make a small program where the output is this using only loops:
123451234123121
my code so far
```
int x;
int y = 1;
for (x=1; x<=5; x++)
{
while(y<=5)
{
printf("%d", y);
y++;
}
}
```
this is what I have so far and don't know where to go next, if anyone could help I'd be grateful.
|
Close. Your outer loop needs to count down, not up, and your inner loop needs to count from 1 to x.
```
int x, y;
for (x=5; x>=1; x--)
{
for (y=1;y<=x;y++)
{
printf("%d", y);
}
printf("\n");
}
```
|
This loop runs infinitely though the value if shift operations becomes zero. Not sure why. Need clarifications.
```
size_t size_of_byte()
{
unsigned int size = 0, i = 1;
while((i << size) > 0)
{
size++;
}
printf("The size of a byte is %u",size);
return size;
}
```
|
Looking for a betteer link, this is from C++, but the behaviour is the same.
http://en.cppreference.com/w/cpp/language/operator_arithmetic
if the value of the right operand is negative or is greater or equal to the number of bits in the promoted left operand, the behavior
is undefined.
The compiler can assume you will never shift more than the width of that integer, consequently, the result will never be 0, so the check is not necessary. This is a perfectly legal optimization, you're relying on UB.
|
Suppose I have a file pointer
```
FILE* infile = fopen("<somefilepath", "r");
```
Now when I dereference the file pointer in gdb then I get
print *infile
│$2 = {_flags = -72539000, _IO_read_ptr = 0x0, _IO_read_end = 0x0,│ _IO_read_base = 0x0, _IO_write_base = 0x0, _IO_write_ptr = 0x0,│ _IO_write_end = 0x0, _IO_buf_base = 0x0, _IO_buf_end = 0x0,│ _IO_save_base = 0x0, _IO_backup_base = 0x0, _IO_save_end = 0x0, _markers = 0x0,│ _chain = 0x7ffff7dd41c0 <_IO_2_1_stderr_>, _fileno = 3, _flags2 = 0,│ _old_offset = 0, _cur_column = 0, _vtable_offset = 0 '\000', _shortbuf = "",│ _lock = 0x6020f0, _offset = -1, __pad1 = 0x0, __pad2 = 0x602100, __pad3 = 0x0,│ __pad4 = 0x0, __pad5 = 0, _mode = 0, _unused2 = '\000' }
Can someone help me understand what this means ?
|
FILE *should be considered an opaque value... Dereferencing it will be platform/library-dependent (and thus not portable).
|
I know the function to create socket:int socket(int domain, int type, int protocol);is located in#include <sys/socket.h>and I can find it on my linux file system.
But where I can find the implementation of this function? I couldn't find a matching one in thekernel source.
|
Look onkernel.orgfor the authentic kernel source. Understand thatsocket(2)is one of the manysyscalls(2)(you need to understand precisely whatsystem callsare) so it is implementedinside the kernelassys_socketand/orsys_socketcalland/ordo_socket; sockets and network code are an entire subsystem (net/) of the kernel, so see itsnet/socket.c, etc etc... See alsosocketcall(2)
Application user-side code are simply issuing a syscall, sosocket(2)is a thin wrapper around a system call (inGNU libcormusl-libcor whatever implementation of theC standard libraryyou are using). See alsothis.
|
I get a result of-858993460throughsizeof()it should be10.
Im coding in C:
```
fscanf(pFile, "%20s", input);
i_sizeOfInput = (sizeof(input) / sizeof(char));
```
i_sizeOfInputis-858993460.
Any idears?
|
To get the length of a string you must usestrlen
```
In your case i_sizeOfInput = strlen(input);
```
The sizeof operator returns the size in bytes of its operand.
EDIT
Reading recent comments I must add that declaring your input variable in that way (char input[] = { ' ' };)you are invokingUndefined Behaviour.
As you can see you are declaring an array with a space of 1 char andfscanfca return a lot of bytes that will be placed out of bounds ofinputvariable.
You must define input as large as the maximun dimention of strings that can be read from file, e.gchar input[128] = {'\0'};
|
I have input time in seconds epoch format.
I need to have struct tm out of this epoch time in seconds.
```
struct tm epoch_time;
int seconds = 1441852;
epoch_time.tm_sec = seconds;
```
My purpose is to have tm structure filled with proper values for years, months, days, hours, minutes, and seconds for the given epoch time in seconds. Any hint in this regard will be helpful. Thanks.
|
```
struct tm epoch_time;
time_t seconds = 1441852;
memcpy(&epoch_time, localtime(&seconds), sizeof (struct tm));
```
This assumes you want local time. If you want GMT, usegmtimeinstead oflocaltime. Note that this will crash on error.
|
This question already has answers here:With arrays, why is it the case that a[5] == 5[a]?(20 answers)Closed8 years ago.
When I read asterisk source code, I found a code line like this:
#define ARRAY_LEN(a) (size_t) (sizeof(a) / sizeof(0[a]))
I often usea[0]or(*a), but they use(0[a]). Could you please help me explain more clearly about this?
|
a[0]is translated by the compiler as*(a+0).0[a]is translated as*(0+a). Hence,a[0]and0[a]are equivalent.
From the C99 standard:
6.5.2.1 Array subscripting2 A postfix expression followed by an expression in square brackets[]is a subscripted designation of an element of an array object. The definition of the subscript operator[]is thatE1[E2]is identical to(*((E1)+(E2))).
|
Why am I getting a "segmentation fault" error when I run this after compiling?
//CODE
```
#include <stdio.h>
#include <string.h>
void main(){
struct name{
char first[20];
char last[20];
} *person;
strcpy(person->first, "jordan");
strcpy(person->last, "davis");
printf("firstname: %s\n", person->first);
printf("lastname: %s\n", person->last);
}
```
|
Becausepersonpointer has not been initialized. So there is no validstruct nameobject when you dereference the pointer.
Either use malloc:
```
person = malloc(sizeof *person);
```
or just declare an object of typestruct nameinstead ofstruct name *(and then don't forget to access your structure members with.operator instead of->).
|
Good evening,
quick question regarding the following code:
```
// Start of main
int i,j;
int row,col;
printf("Enter the values for row and col:\n");
scanf("%d%d",&row,&col);
int **arr=(int**)malloc(row*(sizeof(int*)));
for(i=0; i<row; i++)
{
*(arr+i) = (int*)malloc(sizeof(int)*col);
}
// .. code after this snippet
```
Why am I able to use the variablearras a pointer to a pointer and then re-use it as a pointer inside the for loop ?? Why do I not have to create two seperate variables ?
|
Inside theforloop, you arenotusingarras apointer-to-an-int; you are using*(arr+i)as apointer-to-an-int, which is consistent with dereferencingarr, which is apointer-to-a-pointer-to-an-int.
|
I am trying to find a pseudocode for implementing the "radial blur" using C and OpenMP. "Radial blur" is an operation, in which each pixel is replaced by the average of neighboring pixels. For example for a 3x3 pixel image the centered image's value is given by:
X4=(X1+X3+X5+X7)/4;
and the value of any other is given by:
X0=(X1+X3)2;
I am searching for a 9x9 implementation with 3 processors. Any kind of help would be amazing. Thank you.
|
Can you check the following link?http://www.drdobbs.com/architecture-and-design/faster-image-processing-with-openmp/184405586
|
I have this code:
```
int num[10] ;
sscanf(msg, "%d%d%d%d%", &num[0], &num[1], &num[2], &num[3]);
int x = num[0]; // integer
int y = num[1]; // integer
int z = num[2]; // integer
int c = num[3]; // integer
```
I got problem from the above code, when I write '131249', so the result is:
```
x = 177
y = -8755
z = -21206
c = -246
```
but the expected value should
```
x = 13
y = 12
z = 4
c = 9
```
How to have the expected value, is there any wrong in my code ?
|
If your values length is fixed, you may want to specify the lenght of each value you're trying to capture. Ex :
sscanf(msg, "%2d%2d%1d%1d%", &num[0], &num[1], &num[2], &num[3]);
|
```
//A structure to describe a matrix.
typedef struct matrix{
int x, y, size, original_size, *data;
};
//Function to index matrices.
int get(matrix m, int x, int y)
{
return m.data[m.original_size * (m.x + x) + m.y + y];
}
```
I'm attempting to understand the line m.original_size * (m.x + x) + m.y + y in this C code. I need more elaboration on this line, m.data[m.original_size * (m.x + x) + m.y + y].
My attempt: Data is a pointer, which points to the address of array m.data. But then I get confuse trying to understand the rest of the statement. Especially * (m.x + x) + m.y + y.
|
The structure is designed to represent a matrix (which is stored in*data) and a sub matrix, which is defined as starting at the m.x-th row and the m.y-th column. Hence, theget()function is really to access data in sub matrix, and the x & y indices are transformed to their positions in the original full matrix.
|
I have this code:
```
int num[10] ;
sscanf(msg, "%d%d%d%d%", &num[0], &num[1], &num[2], &num[3]);
int x = num[0]; // integer
int y = num[1]; // integer
int z = num[2]; // integer
int c = num[3]; // integer
```
I got problem from the above code, when I write '131249', so the result is:
```
x = 177
y = -8755
z = -21206
c = -246
```
but the expected value should
```
x = 13
y = 12
z = 4
c = 9
```
How to have the expected value, is there any wrong in my code ?
|
If your values length is fixed, you may want to specify the lenght of each value you're trying to capture. Ex :
sscanf(msg, "%2d%2d%1d%1d%", &num[0], &num[1], &num[2], &num[3]);
|
```
//A structure to describe a matrix.
typedef struct matrix{
int x, y, size, original_size, *data;
};
//Function to index matrices.
int get(matrix m, int x, int y)
{
return m.data[m.original_size * (m.x + x) + m.y + y];
}
```
I'm attempting to understand the line m.original_size * (m.x + x) + m.y + y in this C code. I need more elaboration on this line, m.data[m.original_size * (m.x + x) + m.y + y].
My attempt: Data is a pointer, which points to the address of array m.data. But then I get confuse trying to understand the rest of the statement. Especially * (m.x + x) + m.y + y.
|
The structure is designed to represent a matrix (which is stored in*data) and a sub matrix, which is defined as starting at the m.x-th row and the m.y-th column. Hence, theget()function is really to access data in sub matrix, and the x & y indices are transformed to their positions in the original full matrix.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.