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...
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 aNULLparam...
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(&regex, e, 0); reti = regexec(&regex, c, 0, NULL, 0); if(!reti) return 1; return 0; } int main() { char str[5] = {'0','x','2','F'}; if(reg...
In order to use the+metacharacter, you need to tellregcomp()that you're using theextended POSIX syntax: ``` int reti = regcomp(&regex, 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...
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 t...
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. ...
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_strnse...
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:...
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 t...
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 g...
*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 = ...
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 i...
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 t...
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. ...
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_strnse...
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:...
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 t...
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...
``` 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 s...
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_siz...
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).star...
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 (whic...
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 ...
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(...
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...
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.xctoolc...
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 ...
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 infor...
``` #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); ...
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 ex...
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 c...
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) { pr...
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 t...
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 ...
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 ...
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 cod...
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...
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 c...
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) { pr...
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,...
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 ...
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 ...
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 repla...
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 h...
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 << 1...
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 call...
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); } ...
``` 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 answer...
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 do...
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 s...
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 t...
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 b...
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 ...
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...
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 li...
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...
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 answer...
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 do...
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 s...
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 t...
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 b...
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 ...
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...
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 li...
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...
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*...
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 addres...
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 (siz...
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....
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 lin...
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 g...
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 c...
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. ...
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 (co...
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 c...
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. ...
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 (co...
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_s...
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 s...
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 ...
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 ...
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 the...
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 funct...
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 = a...
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 = a...
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", *((*(&arra...
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 ...
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----- ...
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* ...
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(...
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 t...
++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* ...
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(...
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 t...
++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 t...
++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...
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:...
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; ...
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...
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_b...
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 s...
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. A...
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 g...
``` 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 explai...
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 ...
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("firstn...
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 ...
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 snippe...
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 give...
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 cod...
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...
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 cod...
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...
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.