question
stringlengths
25
894
answer
stringlengths
4
863
``` #include<STDIO.H> ``` It is in upper case but the program (compiles and) runs without any error in C language, but C is case sensitive — how this is possible? ``` #include<STDIO.H> #include<CONIO.H> main() { printf("hello"); getch(); } ```
This works if you are using Windows or another operating system that ignores case on its file system. It doesn't work on Linux and other Unix flavours, because they do care about case (by default). When you add an include statement like#include <any_file.h>, then the C-compiler will ask the operating system to open fileany_file.h. If your operating system doesn't care about case, then it will open any file that matches the pattern. If it, for instance, finds a file namedaNy_fILe.H, it will open the file and present it to the C compiler. The C-compiler will interpret the content of the file - this is the case-sensitive bit of the C language.
I would like to know why my code isn't working if thats ok. Whats supposed to happen is it is supposed to get 9 chars from the user and put them into allocated memory locations. ``` #include <stdio.h> #include <stdlib.h> int main(){ char count, *ptr, *p; ptr = malloc(27); p = ptr; for(int i = 0; i < 9; i++) { *p++ = scanf("%c", &count); } *p = '\0'; puts(ptr); free(ptr); } ```
There are following issues. I assume you want to store characters in memory pointed by ptr. Why are you allocating 27 bytes? You should allocate for 9 characters.ptr = malloc(sizeof(char)*(9+1));// 1 for '\0'if(0 == ptr)return;Scanf returns number of characters read. So you should write scanf like below.scanf("%c", p++);If you want to enter string using scanf, you can use "%s". Loop is not actually required.scanf("%9[^\n]",p); Make these changes. It should work.
c use libcurl curl_easy_perform post, spaces and dot replaced by underscore The code is like the example below. On the other side the received data is wrong: Expect:<Text>data to send...</Text>Actually:<Text>data_to_send___</Text> ``` CURL *curl = curl_easy_init(); if(curl) { const char *data = "<Text>data to send...</Text>"; curl_easy_setopt(curl, CURLOPT_URL, "http://example.com"); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data); } ``` Does anybody know the reason?
That's an incorrect conclusion so the question ends up rather useless. libcurl will send the dataexactlyas you provide it withCURLOPT_POSTFIELDS. If the data end up looking different in some presentation layer of yours, then it was either changed or displayed like that by some other layer/software component.
When I try to execute a c code with the following two lines, ulimit still shows to be unlimited but i want the answer to be 1024. system("ulimit -d 1024"); system("ulimit -d");
If you want to set the ulimit for calling process, usesetrlimit(2), with arguemntRLIMIT_DATA. system()will fork and the ulimit command only affects the child process, not the calling process.
I am extending tools/gatt_service.c from Bluez to create some custom read characteristics for my device. But some of them can take a while to process like a scan wifi SSID. When my server receives the read request from the client, I start the wifi scan (that can take a maximum of 15sc) and I would like to return the list of SSID in the response of the same request. But with the D-Bus API my request always ends after 5sc without waiting until the end of the wifi scan, like a timeout. Is there any way to manage this timeout ? I also tried with the low level Bluez API and it was successful, but I really would like to use the D-BUS API. Thanks !
I finally did a workaround by patching directly the Bluez code. I changed the ATTRIBUTE_TIMEOUT in src/shared/gatt-db.c ``` #define ATTRIBUTE_TIMEOUT 28000 ``` No side effect so far. I just don't know why this value is hard-coded and not changeable from bluethodctl or elsewhere.
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.Closed6 years ago.Improve this question I am currently writing a C program in which I need to recreate ls and a few of its options. I have no idea where to start when it comes with -l. I am looking around for the source code but I can't seem to find anything. Any help pointing me in the right direction to recreating -l would be very helpful.
You can find source code of many GNU commands here :http://git.savannah.gnu.org/gitweb/?p=coreutils.git;a=tree;f=src;h=df809d8aabc8c9207166f3f3f1e814cc62560c8d;hb=master, including ls.Hope this help !
I would like to know why my code isn't working if thats ok. Whats supposed to happen is it is supposed to get 9 chars from the user and put them into allocated memory locations. ``` #include <stdio.h> #include <stdlib.h> int main(){ char count, *ptr, *p; ptr = malloc(27); p = ptr; for(int i = 0; i < 9; i++) { *p++ = scanf("%c", &count); } *p = '\0'; puts(ptr); free(ptr); } ```
There are following issues. I assume you want to store characters in memory pointed by ptr. Why are you allocating 27 bytes? You should allocate for 9 characters.ptr = malloc(sizeof(char)*(9+1));// 1 for '\0'if(0 == ptr)return;Scanf returns number of characters read. So you should write scanf like below.scanf("%c", p++);If you want to enter string using scanf, you can use "%s". Loop is not actually required.scanf("%9[^\n]",p); Make these changes. It should work.
c use libcurl curl_easy_perform post, spaces and dot replaced by underscore The code is like the example below. On the other side the received data is wrong: Expect:<Text>data to send...</Text>Actually:<Text>data_to_send___</Text> ``` CURL *curl = curl_easy_init(); if(curl) { const char *data = "<Text>data to send...</Text>"; curl_easy_setopt(curl, CURLOPT_URL, "http://example.com"); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data); } ``` Does anybody know the reason?
That's an incorrect conclusion so the question ends up rather useless. libcurl will send the dataexactlyas you provide it withCURLOPT_POSTFIELDS. If the data end up looking different in some presentation layer of yours, then it was either changed or displayed like that by some other layer/software component.
When I try to execute a c code with the following two lines, ulimit still shows to be unlimited but i want the answer to be 1024. system("ulimit -d 1024"); system("ulimit -d");
If you want to set the ulimit for calling process, usesetrlimit(2), with arguemntRLIMIT_DATA. system()will fork and the ulimit command only affects the child process, not the calling process.
I am extending tools/gatt_service.c from Bluez to create some custom read characteristics for my device. But some of them can take a while to process like a scan wifi SSID. When my server receives the read request from the client, I start the wifi scan (that can take a maximum of 15sc) and I would like to return the list of SSID in the response of the same request. But with the D-Bus API my request always ends after 5sc without waiting until the end of the wifi scan, like a timeout. Is there any way to manage this timeout ? I also tried with the low level Bluez API and it was successful, but I really would like to use the D-BUS API. Thanks !
I finally did a workaround by patching directly the Bluez code. I changed the ATTRIBUTE_TIMEOUT in src/shared/gatt-db.c ``` #define ATTRIBUTE_TIMEOUT 28000 ``` No side effect so far. I just don't know why this value is hard-coded and not changeable from bluethodctl or elsewhere.
I am trying to use a const FILE *fp to rewind, fscanf and etc. the usual stuff but I run into c4090 error and I am not quite understanding it. ``` int search(const FILE *fp, int patt) { if (fp != NULL) { rewind(fp) //Getting c4090 warning //other statements } } ``` This seems like a basic question and I tried searching for a bit and microsoft manual is mostly what I've got and I don't really understand what they are implying
"This warning can be caused when a pointer to a const or volatile item is assigned to a pointer not declared as pointing to const or volatile." Source:https://msdn.microsoft.com/en-us/library/k77bkb8d.aspx Try: ``` int search(FILE *fp, int patt) { if (fp != NULL) { rewind(fp) //No c4090 warning, Because we can change fp //other statements } } ```
I'm creating a simple network scanning function using nmap and C. I want to use popen() to execute nmap, but nmap takes close to 30 seconds to complete because I'm scanning a wide range of IPs. So, is there a way to check when the command has finished executing? I don't want my C code to hang at the system call, instead I would like to just check a flag or something in a loop that will know when popen/nmap has finished so other parts of my C program don't come to an halt. Is this possible?? Thanks!
I can think of 2 direct ways to do it You couldfork()directly and then establish a way to communicate the two processes, this would be very difficult because IPC is not an easy matter.You could create a new thread withpthread_create()and callpopen()there, it would be a lot easier and you could share data between threads by using an appropriate locking mechanism to prevent race conditions.
``` //#define static /*empty*/ int main() { static int a(); return a(); } static int a() { return 0; } ``` This works fine if I delete (#define static /*empty*/) thestatickeywords, but with thestatics it breaks with:error: static declaration of ‘a’ follows non-static declaration(gcc). What's the reason for this behavior?
It's not valid (and doesn't make sense) to declare a function inside another withstatickeyword. C standard explicitly prohibits this: C11 draft, 6.7.1: The declaration of an identifier for a function that has block scope shall have no explicit storage-class specifier other than extern.
I am trying to use a const FILE *fp to rewind, fscanf and etc. the usual stuff but I run into c4090 error and I am not quite understanding it. ``` int search(const FILE *fp, int patt) { if (fp != NULL) { rewind(fp) //Getting c4090 warning //other statements } } ``` This seems like a basic question and I tried searching for a bit and microsoft manual is mostly what I've got and I don't really understand what they are implying
"This warning can be caused when a pointer to a const or volatile item is assigned to a pointer not declared as pointing to const or volatile." Source:https://msdn.microsoft.com/en-us/library/k77bkb8d.aspx Try: ``` int search(FILE *fp, int patt) { if (fp != NULL) { rewind(fp) //No c4090 warning, Because we can change fp //other statements } } ```
I'm creating a simple network scanning function using nmap and C. I want to use popen() to execute nmap, but nmap takes close to 30 seconds to complete because I'm scanning a wide range of IPs. So, is there a way to check when the command has finished executing? I don't want my C code to hang at the system call, instead I would like to just check a flag or something in a loop that will know when popen/nmap has finished so other parts of my C program don't come to an halt. Is this possible?? Thanks!
I can think of 2 direct ways to do it You couldfork()directly and then establish a way to communicate the two processes, this would be very difficult because IPC is not an easy matter.You could create a new thread withpthread_create()and callpopen()there, it would be a lot easier and you could share data between threads by using an appropriate locking mechanism to prevent race conditions.
I have installed mingw on my arch linux distribution in order to cross compile windows applications. Everything seems to work fine, except when I include Winsock2: ``` x86_64-w64-mingw32-gcc -c -Wall -o tcp.o tcp.c tcp.c:14:24: fatal error: Winsock2.h: No such file or directory #include <Winsock2.h> ``` What package do I miss?
The problem is that in linux, files paths are case sensitive. On Windows you can do: ``` #include <Winsock2.h> ``` while the actual file isC:/Path/To/Include/winsock2.h On linux you have to do ``` #include <winsock2.h> ```
I would like to compile a file c, I get the following error: cannot compile c file with /ZW option I removed the option in the file properties (Windows Runtime extension), but I still have the same error. Thank you
When changing project properties in Visual Studio, remember often need to setConfigurationAll ConfigurationsandPlatformtoAll Platforms. This can be particularly confusing when you are changing the properties of the non-active configuration/platform and your changes don't seem to have any effect. Note that you can use C language files in a UWP project, but you can't consume Windows Runtime APis using C. C++ is required for both C++/CX language extensions as well as the new C++ WinRT language projections.
uvlibUDP accepts event callback function of the following type: ``` typedef void (*uv_udp_recv_cb)(uv_udp_t* handle, ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned flags); ``` There is no info about target port and address likesent_to_addr. Is there way to achieve it? I need this to know on what interface packet received, or to know multicast group. Socket listens on 0.0.0.0:xxxx
IP_PKTINFOhas such a information, but libuv does not expose an API that enables it.
As I was reading, there is a need to usefree(), BUT what happen next? I mean if I got something like that: ``` char word[] = "abc"; char *copy; copy = (char*) malloc(sizeof(char) * (strlen(word) + 1)); strcpy(copy, word); free(copy); printf("%s", copy); ``` It is going to write me "abc". Why?
After usingfree(), your pointercopystill points to the same memory location.free()does not actually delete what is written there in memory but rather tells the memory management that you do not need that part of memory anymore. That is why it still outputsabc. However, your OS could have reassigned that memory to another application or some new thing you allocate in your application. If you are unlucky, you will get an segmentation fault.
This question already has answers here:GDB question: Pretty-Printing a 2D Array?(5 answers)Closed6 years ago. I am trying to debug a program in c++ language with gdb debugger. I have an array[100][100] and want just to see 5 elements of rows and columns and not more. I can handle a 1d array with the following command : ``` display *arr@5 ``` but how can I display a 2d array ? I tried these but failed : ``` display *arr@5*5 display *arr@5 5 ```
You could create a function to print the information the way you want, say: ``` void print_matrix(int matrix[100][100], int number) { int i, j; for (i = 0; i < number; ++i) { for (j = 0; j < number; ++j) std::cout << matrix[i][j] << " "; std::cout << "\n"; } } ``` And then call it on gdb: ``` call print_matrix(arr, 5) ```
I am new to Gstreamer and I want to use it to listen to RTP stream. To do that, I use this pipeline : ``` gst-launch-1.0 udpsrc caps=application/x-rtp port=5000 ! rtpjitterbuffer ! rtpopusdepay ! opusdec ! alsasink ``` I don't know why, but I have some delay (~ 1s) and I want to minimize it. I'm sure that this is not coming from source and transport. If anyone has any ideas :)
So, If anyone has the same problem, this is the properties that helped me : latencyof rtpjitterbufferbuffer-timeandlatency-timeof alsasink And also update gstreamer :)
This question already has answers here:Expand macro inside string literal(2 answers)Closed6 years ago. Lets say I have a define like so: ``` #define MY_FUNC_NAME my_func ``` I want to get a string literal for it, e.g."my_func". I tried using the hash preprocessor operator like so: ``` #define str(s) #s #define MY_FUNC_NAME_LITERAL str(MY_FUNC_NAME) ``` But this would yield"MY_FUNC_NAME"instead of"my_func", as though it does not replace it before creating the literal. Any ideas how to achieve that?
Like theGCC documentationexplains, you need two macros to do that ``` #define xstr(s) str(s) #define str(s) #s #define foo 4 str (foo) ==> "foo" xstr (foo) ==> xstr (4) ==> str (4) ==> "4" ``` Actual answer for this problem: ``` #define str_(s) #s #define str(s) str_(s) #define MY_FUNC_NAME_LITERAL str(MY_FUNC_NAME) #define MY_FUNC_NAME my_func ```
I'm new to C language and I'm trying to save data to a .csv and read the same data in a very simple program. ``` char c; FILE *fp; fp = fopen("file.csv", "w+"); fprintf(fp, "Hello;World\nLine"); fclose(fp); fp = fopen("file.csv", "r"); while (getc(fp) != EOF) { printf("%c", getc(fp)); } fclose(fp); ``` I don't know why the output is wrong: ``` el;ol ie ``` Thanks in advance
Because you are reading a character in the loop condition (so it prints out every other one when printing), and reading another one when printing it out. Try this: ``` int ch; while ((ch=getc(fp)) != EOF) { printf("%c", ch); } ```
I tried ``` print ("السلام عليكم\n"); ``` it outputs ``` ?????? ????? ``` After looking at the generated c code ``` ... g_print ("السلام عليكم\n"); ... ``` it appears that they're using g_print() which it is not doing that same as printf() in C which works perfectly fine with Arabic. So, is there anyway to print arabic text in Vala?
Just add this to the start of your code: ``` Intl.setlocale (LocaleCategory.ALL, ""); ``` By leaving the second parameter an empty string you're loading the LOCALE that the current user has set (which is likely to be a UTF-8 based one on modern Linux systems). Windows is a different story here ... See also: https://valadoc.org/glib-2.0/GLib.Intl.setlocale.htmlprinting utf8 in glibhttps://en.wikipedia.org/wiki/C_localization_functionshttp://en.cppreference.com/w/c/locale/setlocale
Please check the code snippet given below. Pardon me if anything is wrong with the syntax or anything else. I am a newbie trying to learn structure usage in detail and I happened to come across the following sample. I just wanted to know how to accessStu_DetailsfromClass_Details ``` typedef struct { int age; int RollNo; int Rank; char Name[10]; }TypeStudent; typedef struct { char class_name[20]; TypeStudent Students[20]; }TypeClass; const TypeStudent Stu_Details[] = { { 3, 1, 18, "Mahesh"}, { 3, 1, 7, "Kumar"} }; const TypeClass Class_Details[]= { { "Class 10", Stu_Details}, //two students details { "Class 8", 0} //no student details attached }; ```
``` Class_Details[0].Students[0].Name ``` for exemple will be "Mahesh"
So I have the following function. The function takes a target int ** double pointer and copies a source array to it. ``` void copyMatrix(int ** target, int m, int n, int source[m][n]) { int i,j; target = (int **) malloc(m * sizeof(int *)); for (i = 0; i < m; i++) target[i] = (int *)malloc(n * sizeof(int)); for(i=0; i < m; i++){ for(j=0; j < n; j++){ target[i][j] = source[i][j]; } } printf("%d ", target[i][j]); } ``` When i call printf after the for loops, i get a segfault, but if i call printf inside the for loops, it prints target[i][j] correctly. Why is this? I'm tearing my hair out over this...
After the loops,i == mandj == n. They both point 1 item past the max. Arrays in C are zero-indexed, so accessingtarget[n][m]of an array with size[n][m]will give an out-of-bounds access.
I'd like to write a code in C in which the number of characters of a password is declared but I don't know why after using the following algorithm, I get weird answers. ``` #include <stdio.h> #include <stdlib.h> #include<string.h> int main() { int n=1,i=0; char * pass[100]; printf("Enter your pass: "); scanf(" %c",&pass); for (i=0; pass[i]!='0';i++){ n++; } printf("number of characters: %d\n", n); return 0; } ```
To start withchar * pass[100]is probably not what you want although it might work. You just needchar pass[100]. Secondly you are askingscanfto scan for a single character with the%coption. To read a whole string use the%soption. Finally in the line:for (i=0; pass[i]!='0';i++){ '0'does not mean null, it refers to the character 0, i.e. 48 on the ascii charts. You are probably looking for'\0'which means null. Null is used to terminate the strings.
Why does this code output -32768 and not 32768? Looks like an overflow but I cannot figure out where. ``` #include <stdio.h> #include <stdlib.h> int main() { char *buffer = (char*)malloc(sizeof(char)*2); buffer[0] = 0x80; buffer[1] = 0x00; int address = (buffer[0]<<8) | (buffer[1]); printf("%d\n", address); //outputs -32768 return 0; } ```
On your compilercharis signed. On your compiler,0x80is converted to-0x80to fit in a signedchar. Sobuffer[0]holds -128, and((-128)<<8) | (0)evaluates to -32768.
I have a program in C. I need to use a SQLite library to read data from a database. When I includesqlite3.hto my source file I getunresolved symbolerrors onsqlite3functions. If I addlibfile as library I don't get any error but program requiressqlite3.dllto run. I already tried to play with compiler settings but nothing changed. SQLite is written in C and my program is also C. Why do I need a DLL file to use SQLite? How can I remove the DLL dependency. I'm using MCVS2015 community edition IDE.
Therecommendedway of compiling SQLite is todownloadthe amalgamation source code file (sqlite3.c), and to add it to your project.
I have a function similar to this using pointers in C ``` float *compute_avg(float *array, int num_elements) { float sum = 0.f; int i; for (i = 0; i < num_elements; i++) { sum += array[i]; } return sum; } ``` But error occurs "return value type does not match function type".
It's because your function returns afloat *, and you're trying to return afloat. You can just remove the*to change the first line tofloat compute_avg(float *array, int num_elements) You can also declare sum as a float * and then malloc memory for it. Then you should use*sum += array[i];, but remember tofreeit later.
In order to know if wait() has worked, will it be correct to check it like the following? In theory, if wait() does not fail, should return to the parent process the ended child pid, otherwise parent pid will be 1, right? ``` switch (process = fork()) { case -1: // Fork fail perror("Fork failed"); exit(EXIT_FAILURE); case 0: //Child process HERE CODE DOES SOMETHING exit(EXIT_SUCCESS); default: //Parent process pid=wait(&status); if(pid==1){ perror("Wait failed"); }else{ exit(EXIT_SUCCESS); } } ```
Quotingman 2 wait: RETURN VALUEwait(): on success, returns the process ID of the terminated child;on error, -1 is returned. So to check ifwait(2)failed, this should be enough: ``` if (wait(&status) == -1) { perror("wait failed"); exit(1); } ```
For some weird reason my little program over here doesn't show up the way I want to.The last\tbefore Quit for a weird reason doesn't do anything. Can anyone explain me why? ``` #include <stdio.h> int n,litera; void main (void) { n=1; printf("File\tEdit\tView\tCompile\tQuit\n"); printf("Selectati optiunea aleasa:"); } ```
There's nothing really weird about it. SinceCompileis more than 4 letters long, it eats up three spaces into the next tab block. Hence the result. Use two\t\totherwise. Here's a Q&D solution: ``` #include <stdio.h> #define TAB " " int n,litera; int main (void) { n=1; printf("File"TAB"Edit"TAB"View"TAB"Compile"TAB"Quit\n"); printf("Selectati optiunea aleasa:"); return 0; } ```
According to this thread:To Compute log(a+b) Sometimes log_sum is implemented like this: log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a) I'm confused about why this approach is more efficient.. Does anyone have ideas about this?
This approach might be useful, whenais constant (at least for somebvalues), andb<<a(significantly smaller). In this caselog(1 + b/a)could be calculated throughTaylor seriesexpansion fast and with good precision (log1pfunction in some math libraries,another method)
In order to know if wait() has worked, will it be correct to check it like the following? In theory, if wait() does not fail, should return to the parent process the ended child pid, otherwise parent pid will be 1, right? ``` switch (process = fork()) { case -1: // Fork fail perror("Fork failed"); exit(EXIT_FAILURE); case 0: //Child process HERE CODE DOES SOMETHING exit(EXIT_SUCCESS); default: //Parent process pid=wait(&status); if(pid==1){ perror("Wait failed"); }else{ exit(EXIT_SUCCESS); } } ```
Quotingman 2 wait: RETURN VALUEwait(): on success, returns the process ID of the terminated child;on error, -1 is returned. So to check ifwait(2)failed, this should be enough: ``` if (wait(&status) == -1) { perror("wait failed"); exit(1); } ```
For some weird reason my little program over here doesn't show up the way I want to.The last\tbefore Quit for a weird reason doesn't do anything. Can anyone explain me why? ``` #include <stdio.h> int n,litera; void main (void) { n=1; printf("File\tEdit\tView\tCompile\tQuit\n"); printf("Selectati optiunea aleasa:"); } ```
There's nothing really weird about it. SinceCompileis more than 4 letters long, it eats up three spaces into the next tab block. Hence the result. Use two\t\totherwise. Here's a Q&D solution: ``` #include <stdio.h> #define TAB " " int n,litera; int main (void) { n=1; printf("File"TAB"Edit"TAB"View"TAB"Compile"TAB"Quit\n"); printf("Selectati optiunea aleasa:"); return 0; } ```
According to this thread:To Compute log(a+b) Sometimes log_sum is implemented like this: log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a) I'm confused about why this approach is more efficient.. Does anyone have ideas about this?
This approach might be useful, whenais constant (at least for somebvalues), andb<<a(significantly smaller). In this caselog(1 + b/a)could be calculated throughTaylor seriesexpansion fast and with good precision (log1pfunction in some math libraries,another method)
So basically, I have this 2-D array that looks like this. ``` ######...s e......### ``` It suppose to print a * from s-e only if theres a "." , the "#" is like a wall. So I check all the possible location but for some reason its not outputting a "*" to e. I believe it because of something to do with it being out of bound. I did some check for example like ``` if(array.x <=row && array.y<= col && array.x >=0 && array.y >=0) ``` Is this a proper way to check if I'm inside or out of bound? Btw this is an 2d array
Assumingrowis the number of rows,colis the number of columns,array.xandarray.yare the indices, a proper check for indices in bounds is: ``` if(0 <= array.x && array.x < row && 0 <= array.y && array.y < col) { ... } ``` Note the strict inequality withrowandcol.
So I compiled a simple cpp program using clang++ with termux on android, but I can't run the program, I get the following error: ``` $ ./execname -bash: . /execname: Permission denied ```
Are you running on shared storage (under/sdcard)? The file system there does not support executable permissions. Try compiling and running the file directly in the$HOMEdir!
I have a program that returns float numbers.I need to return the answer with exactly two digits after the decimal place and truncate any extra digits rather than rounding. Can someone give me an example please?
There is a special function for truncation:trunc(..)which discards everything after a decimal point. If you want to truncate after a certain number of decimal digits, you can do something like following: ``` trunc(number * 100) / 100 ``` It should be obvious how above line works.
I'm wondering if there is a difference between sizeof(char) and sizeof(char *) : ``` char *s; s = malloc(sizeof(char*)*len + 1); char *s; s = malloc(sizeof(char)*len + 1); ``` Is this the same ?
charis a character andsizeof(char)is defined to be 1. (N15706.5.3.4 The sizeof and _Alignof operators, paragraph 4) char*is apointer toa character andsizeof(char*)depends on the environment. It is typically 4 in 32-bit environment and 8 in 64-bit environment. In typical environment wheresizeof(char*) > sizeof(char),malloc(sizeof(char*)*len + 1)will (at least try to) allocate more memory thanmalloc(sizeof(char)*len + 1)iflenis small enough not to cause integer overflow.
Please consider the following codes ``` #define FIRSTNAME "" #define SECONDNAME "JOHN" # define PATHSAVE(a) func(strcat(strcpy(tmpFileName, appDir), a)) int main() { PATHSAVE(FIRSTNAME SECONDNAME); } ``` By analyzing I found out that value "John" is passed to the function PATHSAVE. By I couldnt understand why two parameters are used in this function PATHSAVE(FIRSTNAME SECONDNAME)
What you wrote will be expanded as follows ``` func(strcat(strcpy(tmpFileName, appDir), "" "JOHN")); ^^ ^^^^^^ || |||||| || SECONDNAME || FIRSTNAME ``` Passing two parameters to a macro require them to be separated by,and not by a space
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.Closed6 years ago.Improve this question Example: My name is ray => ( a ) Another example : Hello the world. =>. ( l h r )
Here's my solution: ``` #include <stdio.h> int main() { char sentence [100]; int i,letter_count=0; printf("Enter a sentence: "); fgets(sentence,100,stdin); for(i=0;sentence [i]!='\0';i++) { if(sentence [i]==' ' || sentence [i+1]=='\0') { if(letter_count%2==1) { printf("%c ",sentence [i-letter_count/2-1]); } letter_count=0; } else { letter_count++; } } putchar('\n'); return 0; } ```
I'm wondering if there is a difference between sizeof(char) and sizeof(char *) : ``` char *s; s = malloc(sizeof(char*)*len + 1); char *s; s = malloc(sizeof(char)*len + 1); ``` Is this the same ?
charis a character andsizeof(char)is defined to be 1. (N15706.5.3.4 The sizeof and _Alignof operators, paragraph 4) char*is apointer toa character andsizeof(char*)depends on the environment. It is typically 4 in 32-bit environment and 8 in 64-bit environment. In typical environment wheresizeof(char*) > sizeof(char),malloc(sizeof(char*)*len + 1)will (at least try to) allocate more memory thanmalloc(sizeof(char)*len + 1)iflenis small enough not to cause integer overflow.
Please consider the following codes ``` #define FIRSTNAME "" #define SECONDNAME "JOHN" # define PATHSAVE(a) func(strcat(strcpy(tmpFileName, appDir), a)) int main() { PATHSAVE(FIRSTNAME SECONDNAME); } ``` By analyzing I found out that value "John" is passed to the function PATHSAVE. By I couldnt understand why two parameters are used in this function PATHSAVE(FIRSTNAME SECONDNAME)
What you wrote will be expanded as follows ``` func(strcat(strcpy(tmpFileName, appDir), "" "JOHN")); ^^ ^^^^^^ || |||||| || SECONDNAME || FIRSTNAME ``` Passing two parameters to a macro require them to be separated by,and not by a space
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.Closed6 years ago.Improve this question Example: My name is ray => ( a ) Another example : Hello the world. =>. ( l h r )
Here's my solution: ``` #include <stdio.h> int main() { char sentence [100]; int i,letter_count=0; printf("Enter a sentence: "); fgets(sentence,100,stdin); for(i=0;sentence [i]!='\0';i++) { if(sentence [i]==' ' || sentence [i+1]=='\0') { if(letter_count%2==1) { printf("%c ",sentence [i-letter_count/2-1]); } letter_count=0; } else { letter_count++; } } putchar('\n'); return 0; } ```
I have this structure as a header file in one of my c projects. ``` struct info{ char name[50]; char address[150]; char country[20]; char region[20]; char postalcode[10]; char phonenumber[15]; char paymethod[15]; }; ``` But can i store a function in a header file? Cause it'd be easier to maintain the whole program.
The appropriate practice is to store the function prototypes (function declarations) in header file. The function implementations go into a ".c" file.
I want to print/log a debug message which has to print debug message if condition met and if after specific interval. Is it possible to make timer ticks part of pre-processor defines?
Is it possible to make timer ticks part of pre-processor defines? Sure it is. Psuedocode: ``` #define LOG_MESSAGE(args) \ if ( enoughTimeHasPassed() ) \ { \ log_message(args); \ } ``` where ``` int enoughTimeHasPassed() { // Return true/false based on whether enough time has passed // since the last call to the function. } void log_message(argtype args) { // Implement the logic to log the message } ```
This question already has answers here:Alternative (K&R) C syntax for function declaration versus prototypes(6 answers)Closed6 years ago. While reading the source code for MINIX, I came across the following: ``` int do_read_write(rw_flag) int rw_flag; /* READING or WRITING */ { ``` It looks like the middle line is used to declare the type of therw_flaginput to the function, but I have never seen this notation before. Is it any different from the following? ``` int do_read_write(int rw_flag) { ``` If not, does it serve any purpose, other than expanding the code so that it can be commented more?
This is a very old C style of declaration, from the first years (1980ies?). Yes, it means the same thing. You should not use it anymore, it is not supported by most compilers anymore, and abandoned for a reason.
I was trying to see the hex representation of floating point numbers and compiled this code with gcc-4.9.2: ``` #include <stdio.h> int main() { double i = 100; printf("%f %x\n", i, (double)i); return 0; } ``` I was surprised to find that everytime I ran the code the hex value printed out changed. What is going on? How can I safely print the hex representation of a floating point number?
The%xformat specifier requires an argument of typeunsigned int. You're giving it an argument of typedouble. The behavior is undefined, which means that as far as the C standard is concernedanythingcan happen -- including changing the output for other specifiers in the same format string. To print the hex representation of a floating-point number, copy it to an array ofunsigned charand print the elements of the array.
I have declared a structure "node" having a member variable 'm' and then defined two variables as below ``` struct node t, *p; ``` Later in the program I assigned the address ofttop: ``` p = &t; ``` To access the member variable I need to usep->m. But I wanted to use the*operator, but writing it*p.mgives error. Why is it so ?
For this you have to see the precedence of the operators. The precedence of.operator is higher than*operator. Writing it like*p.mmakes the compiler think that it is*(p.m). You will have to use(*p).m.
I am working on a project and I need to insert a node in an ordered list. I tried this code but the program keeps on crashing. The calling function is: ``` head = insertorder(node, head); ``` Here is the function definition code: ``` nodeptr_t insertorder(nodeptr_t nn, nodeptr_t head) { nodeptr_t w; w = head; if(head==NULL) return nn; while(w->next!=NULL && w->next->key < nn->key) w = w->next; w->next = nn; nn->next = NULL; return head; } ```
You are losing the tail after inserting a new node. You need to do the following: ``` ... while(w->next!=NULL && w->next->key < nn->key) w = w->next; nn->next = w->next; w->next = nn; ... ```
Here i just want to add one function in u-boot. I need to call one function in start_armboot(). For example, This is hell.h header file. ``` extern void hello(void); ``` This is hell.c file. ``` #include<stdio.h> #include<hell.h> void hello(void) { printf("Hello world"); } ``` This hell.c is added into the common folder,and hell.h is added into the include folder. And then i include this hell.h into lib_arm/board.c. Finally i called hello() function from start_armboot() in lib_arm/board.c. Whenever i compiling it will show the error. ``` lib_arm/libarm.a(board.o): In function `start_armboot': /home/davinci-evm/U-Boot/lib_arm/board.c:389: undefined reference to `hello' make: *** [u-boot] Error 1 ``` Is there any other procedure to add function in u-boot other than this? please help me out.
You must modify the makefile inside common folder. You can simply add ``` obj-y += hell.o ```
I have declared a structure "node" having a member variable 'm' and then defined two variables as below ``` struct node t, *p; ``` Later in the program I assigned the address ofttop: ``` p = &t; ``` To access the member variable I need to usep->m. But I wanted to use the*operator, but writing it*p.mgives error. Why is it so ?
For this you have to see the precedence of the operators. The precedence of.operator is higher than*operator. Writing it like*p.mmakes the compiler think that it is*(p.m). You will have to use(*p).m.
I am working on a project and I need to insert a node in an ordered list. I tried this code but the program keeps on crashing. The calling function is: ``` head = insertorder(node, head); ``` Here is the function definition code: ``` nodeptr_t insertorder(nodeptr_t nn, nodeptr_t head) { nodeptr_t w; w = head; if(head==NULL) return nn; while(w->next!=NULL && w->next->key < nn->key) w = w->next; w->next = nn; nn->next = NULL; return head; } ```
You are losing the tail after inserting a new node. You need to do the following: ``` ... while(w->next!=NULL && w->next->key < nn->key) w = w->next; nn->next = w->next; w->next = nn; ... ```
Here i just want to add one function in u-boot. I need to call one function in start_armboot(). For example, This is hell.h header file. ``` extern void hello(void); ``` This is hell.c file. ``` #include<stdio.h> #include<hell.h> void hello(void) { printf("Hello world"); } ``` This hell.c is added into the common folder,and hell.h is added into the include folder. And then i include this hell.h into lib_arm/board.c. Finally i called hello() function from start_armboot() in lib_arm/board.c. Whenever i compiling it will show the error. ``` lib_arm/libarm.a(board.o): In function `start_armboot': /home/davinci-evm/U-Boot/lib_arm/board.c:389: undefined reference to `hello' make: *** [u-boot] Error 1 ``` Is there any other procedure to add function in u-boot other than this? please help me out.
You must modify the makefile inside common folder. You can simply add ``` obj-y += hell.o ```
I wrote my c program add.c, then preprocessed with cpp, then compiled with CC to obtain an add.s file. Now I would like to open it to see the assembly code. Can't find a way to do it.
The.sfiles are basically assemblersourcefiles, so you can pretty much open them in whatever tool you used to create the.cfiles in the first place. In other words, mere mortals will opt forNotepad++orEmacs, but the true intelligentsia will useVim:-)
This question already has answers here:How to generate a random int in C?(32 answers)Closed6 years ago. Here is my code: ``` alpha = ((rand() % 12) + 1) * 2 + 1; ``` I want to generate randomoddnumbers between 0-25. But except integer13. How can I fix this? Thank you.
Generates number from 0 to 23. If it's a 13, then store 25 in your variable : ``` alpha = ((rand() % 11) + 1) * 2 + 1; if (alpha == 13) alpha = 25; ```
This question already has answers here:Modify a string with pointer [duplicate](4 answers)Closed6 years ago. I have written a program in C to lower a string when compile it in gcc, it crashes when run. But in MSVC program run smoothly. ``` #include<stdio.h> #include<stdlib.h> #include<string.h> char *strlower(char *s){ for ( ; *s; ++s) *s = tolower(*s); return (char *)s; } int main(){ char *c = "HELLO"; strlower(c); printf("%s",c); return 0; } ``` if variablecis array then program works in both compiler. Why not work when using pointer in gcc ?
In C all string literals areread onlyarrays of characters. Trying to modify a string literal leads toundefined behavior. That's the reason you should only useconst char *when having pointers to string literals. Try to use your own array instead: ``` char c[] = "HELLO"; ```
I have achar*to where I want to set the byte, from malloc. How do I set it to 1 or 0, for example?
Assign to your dereferenced pointer: ``` //This will (obviously) set it to 1 *your_pointer = 1; //This will set it to 0 *your_pointer = 0; ```
My professor writes his C variable assignments like this: ``` int a= 10; /*or*/ double t; t= 0.5; ``` instead of ``` int a = 10; /*or*/ double t; t = 0.5; ``` He encouraged his students to do the same and mentioned that there was a specific reason as to why he does that, but never explained it. Is it a preprocessing thing? I see no particular reason why writing it without the first space is better.
It matters not at all. In fact, ``` int a ;;;;; a = 5 ; ``` is just as functional, just utterly unreadable. Pick a style and stick with it. (Don't use this style)
Given the following: ``` struct tm tm; time_t gps_epoch_to_epoch_diff; memset(&tm, 0, sizeof(struct tm)); tm.tm_year = 70; tm.tm_mon = 1; tm.tm_mday = 1; gps_epoch_to_epoch_diff = timegm(&tm); printf("sec = %lus\n", gps_epoch_to_epoch_diff); ``` I would expect the output to be sec = 0s However, I am getting: sec = 2678400s Why?
``` tm.tm_year = 70; tm.tm_mon = 1; tm.tm_mday = 1; ``` You are using1as month, which is february, astm_mon is zero-based. Use0and you should get your desired result.
``` char msg[100] = {’C’,’P’,’R’,‘E’,‘\0’,‘2’,‘8’, ‘8’,‘\0’}; int my_length = 0xFFFFFFFF; my_length = strlen(msg); ``` I thought it is nine, however, the answer is 4. anyone can explain? thanks
strlenwill stop counting as soon as it hits a null terminator (as C uses null terminated strings and expects to only find them at the end of a string). You have four characters before your first null terminator, therefore the length is 4.
In code created by Apple, there is this line: ``` CMTimeMakeWithSeconds( newDurationSeconds, 1000*1000*1000 ) ``` Is there any reason to express1,000,000,000as1000*1000*1000? Why not1000^3for that matter?
One reason to declare constants in a multiplicative way is to improve readability, while the run-time performance is not affected. Also, to indicate that the writer was thinking in a multiplicative manner about the number. Consider this: ``` double memoryBytes = 1024 * 1024 * 1024; ``` It's clearly better than: ``` double memoryBytes = 1073741824; ``` as the latter doesn't look, at first glance, the third power of 1024. As Amin Negm-Awad mentioned, the^operator is the binaryXOR. Many languages lack the built-in, compile-time exponentiation operator, hence the multiplication.
I want to be able to set or clear (multiple) bits of auintX_t t. iis a runtime variable (uintX_t).bis a runtime variable (uintX_t) which is constrained to be0or1. maskis a compile-time constant. Is there a better way than: ``` i = b ? (i | mask) : (i & ~mask) ``` I'm looking to avoid branching, if that's possible. Target is ARM, if it matters.
Exploiting the fact that-1uis the value with all bits set: ``` i = (i & ~mask) | (mask & -b); ``` or ``` i ^= (i ^ -b) & mask; ``` The second approach reduces the number of operations and code size. The first approach may still be faster on a superscalar architecture because some operations can be executed in parallel.
I always usecharasunsigned charandwchar_taswint_t. Given that, does there exist a solution to change function interfaces to use those types with or without recompiling glibc? See also this question:How to change wchar.h to make wchar_t the same type as wint_t?
You can pass a command line option to the compiler to makecharunsigned by default. Changing the interface to standard library functions by redefiningcharwith macros and typedefs is not the correct way to achieve your goal. For gcc and clang, use-funsigned-char. For Visual-C++, use-Jor/J. The wide character typewchar_tis system specific, it typically 32-bit wide on linux systems and wherever the glibc is used, but only 16-bit wide for the Microsoft tools for historical reasons. Changing this type will cause compatibility problems between the compiler and the libraries, don't even think about it.
I'm trying to solve how save nodes of graph. Every node can have more ancestors and more descendants. Now I have this struct: ``` struct Node { int m_Value; int m_Index; // end Node in m_Nodes int m_Length; // actual size of m_Nodes and m_Prev (for realloc) Node* m_Nodes; // dynamic array (descendants) Node* m_Prev; // dynamic array (ancestors) } ``` I'm not sure if this is the best way. The graph can look like this: ``` 1 2 3 4 Edges: [1,2], [1,3], [2,4], [3,4], [4,1] ``` Thank you for your opinions.
You can save edge and point separately.And you need a function to get all edge of one point. so the memory malloc & free operation me be less
I am getting a segmentation fault error while trying to use fscanf to read from a file into a string, any help would be greatly appreciated. ``` int main() { char temp[100]; FILE *fp = fopen("test.txt", "r"); if (fp == NULL) { printf("error"); } memset(temp, 0, strlen(temp)); while (fscanf(fp,"%s", temp)==1) { } return 0; } ```
Thestrlenfunction does something along these lines: ``` int strlen(char *s) { int len = 0; while(*s++) len++; return len; } ``` In other words, it will return the location of the first null character it encounters. If you haven't already initialized your string, then the pointer will probably get incremented out of the array bounds and into some other part of the process' memory in search of the null terminator (which makes it segfault). To address this issue, replace the argument tomemsetwithsizeof(temp).
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.Closed6 years ago.Improve this question Our devices have Linux OS installed on them. When the box reboots, it will contact the servers, get the time from servers and this time will be set as local time on the device. Can any one please let me know if there is any way to check whether this time is valid or not.
In C,time()returns(time_t)(-1)to indicate "the calendar time is not available." Ifmkitme()fails, it returns(time_t)(-1)when "the calendar time cannot be represented". Testing the result oftime()may be a sufficient "way to check whether this time is valid or not." The value(time_t)(-1)is returned if the calendar time is not available. C11dr §7.27.2.4 3
I have two static libraries namedlibx.aandliby.a. libx.ais compiled withgcc -g; whileliby.ais compiled withgcc -O3. I want to link them two into a single executable. Is it viable? Is it harmful?
Yes, it is viable, it isn't harmful as long as the optimizations don't change the ABI (of function calls, or of floating point arithmetic/representation, etc.). Although even in those cases, I believe all necessary information is already compiled in or the linker resolves the issues.
I'm trying to solve how save nodes of graph. Every node can have more ancestors and more descendants. Now I have this struct: ``` struct Node { int m_Value; int m_Index; // end Node in m_Nodes int m_Length; // actual size of m_Nodes and m_Prev (for realloc) Node* m_Nodes; // dynamic array (descendants) Node* m_Prev; // dynamic array (ancestors) } ``` I'm not sure if this is the best way. The graph can look like this: ``` 1 2 3 4 Edges: [1,2], [1,3], [2,4], [3,4], [4,1] ``` Thank you for your opinions.
You can save edge and point separately.And you need a function to get all edge of one point. so the memory malloc & free operation me be less
I am getting a segmentation fault error while trying to use fscanf to read from a file into a string, any help would be greatly appreciated. ``` int main() { char temp[100]; FILE *fp = fopen("test.txt", "r"); if (fp == NULL) { printf("error"); } memset(temp, 0, strlen(temp)); while (fscanf(fp,"%s", temp)==1) { } return 0; } ```
Thestrlenfunction does something along these lines: ``` int strlen(char *s) { int len = 0; while(*s++) len++; return len; } ``` In other words, it will return the location of the first null character it encounters. If you haven't already initialized your string, then the pointer will probably get incremented out of the array bounds and into some other part of the process' memory in search of the null terminator (which makes it segfault). To address this issue, replace the argument tomemsetwithsizeof(temp).
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.Closed6 years ago.Improve this question Our devices have Linux OS installed on them. When the box reboots, it will contact the servers, get the time from servers and this time will be set as local time on the device. Can any one please let me know if there is any way to check whether this time is valid or not.
In C,time()returns(time_t)(-1)to indicate "the calendar time is not available." Ifmkitme()fails, it returns(time_t)(-1)when "the calendar time cannot be represented". Testing the result oftime()may be a sufficient "way to check whether this time is valid or not." The value(time_t)(-1)is returned if the calendar time is not available. C11dr §7.27.2.4 3
I have two static libraries namedlibx.aandliby.a. libx.ais compiled withgcc -g; whileliby.ais compiled withgcc -O3. I want to link them two into a single executable. Is it viable? Is it harmful?
Yes, it is viable, it isn't harmful as long as the optimizations don't change the ABI (of function calls, or of floating point arithmetic/representation, etc.). Although even in those cases, I believe all necessary information is already compiled in or the linker resolves the issues.
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.Closed6 years ago.Improve this question Our devices have Linux OS installed on them. When the box reboots, it will contact the servers, get the time from servers and this time will be set as local time on the device. Can any one please let me know if there is any way to check whether this time is valid or not.
In C,time()returns(time_t)(-1)to indicate "the calendar time is not available." Ifmkitme()fails, it returns(time_t)(-1)when "the calendar time cannot be represented". Testing the result oftime()may be a sufficient "way to check whether this time is valid or not." The value(time_t)(-1)is returned if the calendar time is not available. C11dr §7.27.2.4 3
I have two static libraries namedlibx.aandliby.a. libx.ais compiled withgcc -g; whileliby.ais compiled withgcc -O3. I want to link them two into a single executable. Is it viable? Is it harmful?
Yes, it is viable, it isn't harmful as long as the optimizations don't change the ABI (of function calls, or of floating point arithmetic/representation, etc.). Although even in those cases, I believe all necessary information is already compiled in or the linker resolves the issues.
There are two variablesaandb, and I want to get data from the user. The data can be a number from1to1000or#, and they should be apart by a space. So how to get this kind of input from the user?
In general, this is too broad a scenario to provide exactanswer. However, I'll be happy to provide you the idea. Read user input usingfgets().Tokenize the input using delimiter (space, here) bystrtok().Use appropriate converter functions (example:strtol()) to check and convert the inputs. Now choose a language, write the code and come back if you have any specific issue / question to be addressed / answered.
This question already has an answer here:How to read / parse input in C? The FAQ(1 answer)Closed6 years ago. ``` #include<stdio.h> int main() { char a[10]; for(int i=0; i<5; i++) { printf("\nEnter a character: "); scanf("%c",&a[i]); } } ``` In this loop, the program first asks the question normally. But in the second loop the program doesn't give me option to input a character and immediately runs the third loop. Likewise, all the even iterations are skipped.
I agree with @Keine You should be able to get the expected output by adding a space before the % Corrected code ``` #include<stdio.h> int main() { char a[10]; for(int i=0; i<5; i++) { printf("\nEnter a character: "); scanf(" %c",&a[i]); } } ``` SOURCEhttps://gsamaras.wordpress.com/code/caution-when-reading-char-with-scanf-c/
I'm trying to add a list to the task struct in sched.h in linux kernel (2.4.14-18). I've added the member ``` list_t waitList ``` in the task_struct, and added ``` waitList: LIST_HEAD_INIT(tsk.waitList) ``` to the INIT_TASK macro. I get a kernel oops when i compile and load the kernel. Is there anything else i need to do and missed?
The problem was i added the new member in the middle of the struct, which messed up initializing the init process. Moving it to the end of the task struct solved the problem.
How do i convert an integer to LARGE_INTEGER? For example, when I want to trigger a timer immediately: ``` LARGE_INTEGER zero; zero.QuadPart = 0; KeSetTimer(pTimer, zero, pDpc); ``` Is there any way to convert 0 to LARGE_INTEGER? So I could do this instead: ``` KeSetTimer(pTimer, (SomeType)0, pDpc); ``` I have tried: ``` KeSetTimer(pTimer, (LARGE_INTEGER )0, pDpc); ``` But it doesn't work. I have Googled, but couldn't find any help.
LARGE_INTEGERis astruct. It is not possible to cast a value to a struct type. You need to create an instance of the struct and set its fields as needed. For example: ``` LARGE_INTEGER intToLargeInt(int i) { LARGE_INTEGER li; li.QuadPart = i; return li; } ``` You can then use it like this: ``` KeSetTimer(pTimer, intToLargeInt(0), pDpc); ```
``` char t[] = {'a','b','$'}; char nt[] = {'S','A'}; char table[2][3][2] = { {"AA","AA",""}, {"aA","b",""} }; void main(){ printf("%s",table[0][0]); } ``` Output: AAAA The output should beAA, can somebody help me out,can't figure out the problem.
Your array doesn't have space for null terminator. The right most dimension oftablemust be at least 3 in order to use the elements as C-strings. You are now accessing out-of-bounds of the array (when you print it using%sin theprintf()) which isundefined behaviour. ``` char table[2][3][3] = ... ``` Similarly adjust the length if you are going to have string literals with greater lengths. Btw,void main()is not a standard signature formain(). Useint main(void)or similar.
How do I make an Edit Control have its width and height as 100% of the window. A good example of this is the Edit Control in Notepad. Up till now, I've been setting the size of controls in the CreateWindow() function as static integers. e.g. ``` CreateWindow("EDIT", NULL, WS_CHILD | WS_VISIBLE, 0, 0, 640, 480, hWnd, NULL, NULL, NULL); ``` I am using C and Visual Studio 2015. Thanks in advance.
You have to handleWM_SIZEmessages in your main window procedure and useSetWindowPosAPI call to resize an edit control.
I am trying to compile a C program and am required to use these flags. I was hoping you could tell me why I am getting these errors. Command: ``` gcc -ansi –Wall –pedantic stack.c ``` Output: gcc: –Wall: No such file or directorygcc: –pedantic: No such file or directory
It's ``` gcc -ansi -Wall -pedantic ``` You're using one of those dashes:Dash(specifically, you are using en-dash U+2013). You need to use minus sign-instead
I cant find a way to convert guint8 to uint32_t in C I tried: ``` uint32_t *uint32_value = (uint32_t *)guint8_value; ``` but it says: ``` warning: cast to pointer from integer of different size [-Wint-to-pointer-cast] uint32_t *uint32_value = (uint32_t *)guint8_value ^ warning: assignment makes integer from pointer without a cast [-Wint-conversion] uint32_t *uint32_value = (uint32_t *)guint8_value ^ ```
You aren't casting fromguint8touint32_t. You are casting from an integer (guint8) to a pointer to an integer (uint32_t*) The correct code is very simple: ``` uint32_t uint32_value = guint8_value; ```
I am programming a MAX32 Micro controller in MPLAB. I want to use the UART protocol to interact with my terminal (I am developing on a mac). Is this possible? Can someone point me in the right direction to get started?
Read Wikipedia UART ArticleRead Reference Manual of your µC, Chapter "...UART..."Get example Code for this issue from your Reference Manual or Programming Manual or Internet ArticlesProgram your boardConnect your Board with your PC via Cable (USB, RS232 to USB (virtual RS232) or UART to USB)Open Terminal Program i.e. TeraTermCheck your Settings i.e. Baud RateTry it
``` void viewonechar(){ char name[25], c[25]; int n; fp = fopen("Phonebook.txt","r"); printf ("\n\n Enter Character : "); scanf ("%s",c); fscanf (fp, "%s %d", name, &n); while (!feof(fp)){ if ((strcmp(c, name[0])) == 0){ \\ Warning in here printf (" %s +880%d\n",name, n); } fscanf (fp, "%s %d", name, &n); } printf ("\n\n"); fclose(fp); menu(); } ``` When i compile the code, on the marked line this warning appears, "Passing argument 2 of strcmp makes pointer from integer without a cast". What exactly am i doing wrong?
int strcmp ( const char * str1, const char * str2 ); Sincenameis an array ofchar,name[0]is achar.strcmptakescharpointers as an arguments, so thecharyou have supplied is implicitly cast to an int-type and then - to the pointer, which produces an undefined behavior and most likely will lead to the segfault.
In the C code I am analyzing, there are a lot of multidimensional (struct) arrays which are initialized with a different number of curly brackets e.g.{{0}}or{{{0}}}. However, replacing these by{0}also works perfectly. Is there a (functional) difference between using one or more sets of curly brackets ({}) occurrences ?
No, there is no functional difference. The C standard allows to leave out intermediate{}. In particular, the form{ 0 }is an initializer that can be used for all data types.
I'm trying to add a list to the task struct in sched.h in linux kernel (2.4.14-18). I've added the member ``` list_t waitList ``` in the task_struct, and added ``` waitList: LIST_HEAD_INIT(tsk.waitList) ``` to the INIT_TASK macro. I get a kernel oops when i compile and load the kernel. Is there anything else i need to do and missed?
The problem was i added the new member in the middle of the struct, which messed up initializing the init process. Moving it to the end of the task struct solved the problem.
How do i convert an integer to LARGE_INTEGER? For example, when I want to trigger a timer immediately: ``` LARGE_INTEGER zero; zero.QuadPart = 0; KeSetTimer(pTimer, zero, pDpc); ``` Is there any way to convert 0 to LARGE_INTEGER? So I could do this instead: ``` KeSetTimer(pTimer, (SomeType)0, pDpc); ``` I have tried: ``` KeSetTimer(pTimer, (LARGE_INTEGER )0, pDpc); ``` But it doesn't work. I have Googled, but couldn't find any help.
LARGE_INTEGERis astruct. It is not possible to cast a value to a struct type. You need to create an instance of the struct and set its fields as needed. For example: ``` LARGE_INTEGER intToLargeInt(int i) { LARGE_INTEGER li; li.QuadPart = i; return li; } ``` You can then use it like this: ``` KeSetTimer(pTimer, intToLargeInt(0), pDpc); ```
``` char t[] = {'a','b','$'}; char nt[] = {'S','A'}; char table[2][3][2] = { {"AA","AA",""}, {"aA","b",""} }; void main(){ printf("%s",table[0][0]); } ``` Output: AAAA The output should beAA, can somebody help me out,can't figure out the problem.
Your array doesn't have space for null terminator. The right most dimension oftablemust be at least 3 in order to use the elements as C-strings. You are now accessing out-of-bounds of the array (when you print it using%sin theprintf()) which isundefined behaviour. ``` char table[2][3][3] = ... ``` Similarly adjust the length if you are going to have string literals with greater lengths. Btw,void main()is not a standard signature formain(). Useint main(void)or similar.
I was browsing github the other day and found this piece of code in C++. ``` order[i]= order[i]+order[r]-(order[r]=order[i]); ``` Why is there 2 equal signs in a line of code? I have never seen this before.
The assignment operator=returns anLVALUE, meaning a value can be further assigned to it. Further, this is poor coding in general, as it's hideous. The author would be better off doing separate assignments over multiple lines, as it's easier to read, less prone to errors while implementing (as an extension of readability), the optimizer will likely generate similar code in either case, etc. Also, this kind of code often leads to a common duplicate question on SO:sequence points, and why this code is horrible. Edit:And as others have pointed out, it invokes UB. Axe it.
I am dealing with linked lists, and am having issues moving to the next element of the Linked List. the error that I get is:error: incompatible types when assigning to type 'item' from type 'struct item * Here is the code: ``` typedef struct item { float size; struct item *next; } item; item head, curr, tail; ``` ... ``` head.next = (item*) malloc(sizeof(item)); curr = head.next; ``` Thanks for your help.
In this assignment statement ``` curr = head.next; ``` currhas typeitemwhilehead.nexthas typeitem *. That is the first one is a structure object and the second one is a pointer. They are incompatible. Thus the compiler issues an error. You should declare variablecurrlike pointer ``` item *curr; ```
This question already has an answer here:How do you determine using stat() whether a file is a symbolic link?(1 answer)Closed6 years ago. I am dealing with symbolic links using C posix in linux. I detect a file and I have to differentiate between a regular file and a symbolic link. Now I do the next: ``` if(S_ISREG(direct_info.st_mode)) { // deal with regular file } else if(S_ISLNK(direct_info.st_mode)) { // deal with symbolic link } ``` the problem is that when the file is a symbolic link the flow of the execution enter at the first if. That is, when is a symbolic link also enter in theS_ISREGcondition. So, what can i do to distinguish between both?
You are probably usingstat()to get the file modes.stat()actually returns the info about the target, not the link itself. So, in order to get the information about the link itself you need to uselstat().
This question already has answers here:What are the use cases of SO_REUSEADDR?(2 answers)Closed4 years ago. I am trying to understand a multicast code, and I don't understand the utilities of a little part : ``` int fd_socket = socket(AF_INET, SOCK_DGRAM, 0); u_int yes = 1; setsockopt(fd_socket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); ``` I don't understand the utilities of thesetsockoptfunction. I understand that this function permits to modify the socket in the kernel, andSOL_SOCKETis because my modification is about the level of the socket and not of the level of a protocol. I don't understandSO_REUSEADDR.
For UDP sockets, setting theSO_REUSEADDRoption allows multiple sockets to be open on the same port. If those sockets are also joined to a multicast group, any multicast packet coming in to that group and port will be delivered to all sockets open on that port.
I have to initialize a char array to 0's. I did it like ``` char array[256] = {0}; ``` I wanted to check if it worked so I tried testing it ``` #include <stdio.h> int main() { char s[256] = {0}; printf("%c\n", s[10]); return 0; } ``` After I compile and run it, the command line output shows nothing. What am I missing ? Perhaps I initialized the array in a wrong manner ?
TL;DR --%cis the character representation. Use%dto see the decimal0value. Related , fromC11, chapter §7.21.6.1, (emphasis mine) cIf nollength modifier is present, theintargument is converted to anunsigned char,and the resulting character is written. FYI, see the list ofprintablevalues. That said, for a hosted environment,int main()should beint main(void), at least to conform to the standard.
I tried to portmcode tocorcpp. In my code there is a line ``` A = sparse(I,J,IA,nR,nC); ``` which converts row indexI, col indexJ, and dataIAto sparse matrixAwith sizenR x nC. Is there any equivalent code with C++ or C? An naïve algorithm to duplicate result in full matrix is ``` double *A; A = malloc(sizeof(double)*nR*nC); memset(A, 0, sizeof(double)); for(k=0; k<size_of_IA; k++) A[I[k]*nC + J[k]] += IA[k]; ``` Note that if there is common indices, the value is not over overwritten, but accumulated.
Eigen is an example of a C++ math matrix library that cobtains sparse matrices. It overloads operators to make it feel like a built in feature. There are many C and C++ matrix libraries. None ship as part ofstd, nor is there anything built in. Writing a good sparse matrix library would be quite hard; your best bet is finding a pre-written one. Recommendation questions are off topic
I would like to allow the user to only put input in a specific format.The format:a=1,b=-2,c=3for example. Spaces are allowed inbetween the commas and the characters.I'm using:if (scanf("a=%lf,b=%lf,c=%lf",&a,&b,&c) == 1)but for some reason it doesn't work. How can I fix it?
You are converting 3 numbers, the return value should be 3 if all conversions are successful. Also note that%lfignores spacesbeforethe number. If you also want to ignore spaces around the,and before the=or thea, add a space in the format string: ``` double a, b, c; if (scanf(" a =%lf , b =%lf , c =%lf", &a, &b, &c) == 3) { /* conversion was successful, 3 numbers parsed */ ... } ``` Note however thatscanf()will not ignore just space characters, it will ignore and whitespace characters, including newlines, tabs, etc.
I have that code and I want my loop finish when user gives "###". ``` int main(){ char s[10]; printf("Give string: "); fgets(s,11,stdin); do{ printf("Give string: "); fgets(s,11,stdin); }while ( s!="###" ); return 0; } ``` So far it's ok, but when the user gives an input bigger than 11 characters I have multiple prints of "Give String". I try it withscanfand I did it right. Can anyone give me a solution to do it withfgets?I mean the output looks like this.
C string doesn't support direct comparison, you would needstrcmpfor that, so while ( s!="###" )should bewhile(strcmp(s,"###")) Also you'd need to remove\nfromfgets(so asstrcmpto ignore\n). So thedo..whileshould look like: ``` do{ printf("Give string: "); fgets(s,11,stdin); s[strlen(s) - 1] = '\0'; } while (strcmp(s,"###")); ```
Should we consider recursive call stack as auxiliary space used by the program? I think it should be considered only when calculating space complexity, but not in calculating the auxiliary space. Auxiliary Space is the extra space or temporary space used by an algorithm. Space Complexity of an algorithm is total space taken by the algorithm with respect to the input size.
If you're actually relying on variables in outer calls — if you'll need them again after your innermost call returns — then yes, they should be included in the auxiliary space. But if all you have aretail calls, and the only reason your stack is growing is that your compiler doesn't support tail call optimization, then I don't think I would consider that in the auxiliary space of the (abstract)algorithm, even though your actualimplementationwill end up taking up that space.
``` printf( "%3o\t%2x\t%3d\t%c\n", c = getchar(), c, c, c ); ``` I'm getting a warning that says "unsequenced modification and access to 'c' [-Wunsequenced]". The error is fairly easy to fix; all I have to do is separategetchar()fromprintf(), but I just want to have a better understanding of why this instruction is producing a warning, and what would go wrong if I actually ran it. Does this have anything to do with the implementation ofprintf()using CPP macros for the variable-length argument list?
The order in which arguments passed to a function call are evaluated isunspecified. There is no guarantee that the result ofgetchar()will be assigned tocbefore the last threecarguments are read. Callingc = getchar()outside of the function call fixes the issue.
I am writing some code in C (not C99) and I think I have a need for several global arrays. I am taking in data from several text files I don't yet know the size of, and I need to store these values and have them available in several different methods. I already have written code for reading the text files into an array, but if an array isn't the best choice I am sure I could rewrite it. If you had encountered this situation, what would you do? I don't necessarily need code examples, just ideas.
Usedynamic allocation: ``` int* pData; char* pData2; int main() { ... pData = malloc(count * sizeof *pData); // uninitialized pData2 = calloc(count, sizeof *pData2); // zero-initialized /* work on your arrays */ free(pData); free(pData2); ... } ```