question
stringlengths
25
894
answer
stringlengths
4
863
I know, there are some solved solutions here on stackoverflow. But I don't know why doesn't mine one work. ``` char *ink[90] strcpy(ink, "hi"); printf("stepiii %c \n",ink[0] ); printf("ascii %d\n",ink[0] ); ``` Instead of "ascii 104" returns bad value like "ascii 26984" What am I doing wrong?
In your code, ``` char *ink[90] ``` is wrong. You don't need an array of pointers, as seen in the rest of the snippet. Change that to ``` char ink[90]= {0}; ``` In case you're wondering about the previous output, that code invokedundefined behavior. So, the output is essentially meaningless and MUST not be trusted.
I'm porting some Arduino code to a mcu in pure c. The data typebyteis used in the arduino code which is not supported by the compiler. I'm wondering which data byte should I useuint8_torunsigned char? Which is more correct? I'm relatively new to coding. I gather it depends what the intent of the variable. The variable will store hex data from this camera (screen shot of output). sample output ``` byte incomingbyte; void loop() { byte a[32]; int ii; while(Serial2.available()>0) { incomingbyte=Serial2.read(); } } ``` Many thanks
According tothis linkan arduino byte is an unsigned 8 bit value. I personally would use the more expressiveuint8_t, but anunsigned charwould work as well. What type is used on the new platform to return a byte received from the serial port? Might also want to check out thisquestion.
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 Basically which one of the Codes will return 0, faster ? // if the answer is "the same" because the code is simple than imagine a more complex code variant written in the same way but with more code. Code 1: ``` int a = 0; if(a == 1){ return 1; }else{ return 0; } ``` Code 2: ``` int a = 0; if(a == 1){ return 1; } return 0; ```
There will be no difference in the compiler generated code. Theelseis unnecessary but may be written for clarity.
I've encountered to this following code during my C learning. I've paste it into CodeBlocks therefore I know the output but (here's my question) how it's done? Can you explain it to me? ``` #include <stdio.h> int main() { unsigned char t[10] = {0,1,2,3,4,5,6,7,8,9}; unsigned short *w; w = (unsigned int*) &t; printf("%d\n",*w++); printf("%d\n",*w++); printf("%d\n",*w++); return 0; } ```
Beware that this code, as is, contains errors: bad cast, undefined behavior and platform dependent results... This is pointer arithmetic.winitially points to the content at the address of the first element oft(this is whatw = (unsigned short *)&tmeans). Then, hereafter, you access this memory as containing successivesshorts. At the same time the pointer is moved from ashortto its successor.
I know, there are some solved solutions here on stackoverflow. But I don't know why doesn't mine one work. ``` char *ink[90] strcpy(ink, "hi"); printf("stepiii %c \n",ink[0] ); printf("ascii %d\n",ink[0] ); ``` Instead of "ascii 104" returns bad value like "ascii 26984" What am I doing wrong?
In your code, ``` char *ink[90] ``` is wrong. You don't need an array of pointers, as seen in the rest of the snippet. Change that to ``` char ink[90]= {0}; ``` In case you're wondering about the previous output, that code invokedundefined behavior. So, the output is essentially meaningless and MUST not be trusted.
How can I get the error number or error string returned by therecv()in socket communication,recv()returns-1as read size which means some error has occurred. I want to know the specific reason for the error. so how can I get that.
You need to includeerrno.hand use theerrnoglobal variable to check the last error code. Also, you can usestrerror()to print a locale aware string explaining the error. Example ``` #include <errno.h> ssize_t size; if ((size = recv( ... )) == -1) { fprintf(stderr, "recv: %s (%d)\n", strerror(errno), errno); } ```
I have following text include control character,please see the image ,these control character does not display when I copy from Notepad++ to paste in this question Have any way to grab just "HIEUDT" string in this text ? I have no idea about substring function with control character In another language ,maybe I will using a regex start with\acharacter and0x04,but in C I have no experience about it
You can use standard string functions for this: ``` char *start = memchr(data, '\x07', datalen); start++; char *end = memchr(start, '\x14', datalen-(start-data)); int len = end - start; char str[len+1]; memcpy(str, data, len); str[len] = '\0'; ``` You must of course check ifmemchrdoes not returnNULLeach time.
Hi I want to declare a 12 bit variable in C or any "unconventional" size variable (a variable that is not in the order of 2^n). how would I do that. I looked everywhere and I couldn't find anything. If that is not possible how would you go about saving certain data in its own variable.
Use a bitfield: ``` struct { unsigned int twelve_bits: 12; } wrapper; ```
I'm a beginner in programming and while studying lists in C I found this function and don't know what it does. Can someone explain please. ``` int fun(list_t *list) { return list == NULL ? 0 : list->value + fun(list->next); } ``` I think its a shorter if else statement for ``` if (list == NULL) return 0; else { return list->value; fun(list->next); } ``` Is this right or am I misreading it?
The? :is called theConditional (ternary) operator: ``` return list == NULL ? 0 : list->value + fun(list->next); ``` Is the same as: ``` if(list == NULL) { return 0; } else { return list->value + fun(list->next); } ``` Or more clearly: ``` return (list->value + fun(list->next)); ``` The sum will be evaluated first, and the result is returned.
So i've make a program about an char array that is dinamically allocated, the program is not yet finished but i've got some different return values after i run the program, no warnings, no errors in compiler so i don't know why i get this also sometimes the program crashes.. ``` #include <stdlib.h> #include <stdio.h> #include <malloc.h> #include <string.h> int main(){ int n,i; char *tab=NULL; printf("New size of array: "); scanf("%d",&n); tab=(char*)malloc(n*sizeof(char)); memset(tab,'X',n*sizeof(tab)); for(i=0;i<n;i++) printf("%c",tab[i]); free(tab); return 0; } ```
In your memset you write n * sizeof(tab), I think you wanted to write : n * sizeof(char) You can also add a +1 add the end of your malloc and check the return value, just for security.
I just don't know what this line means.: ``` a = b%4 == 0 && b%100 != 0 || b%400 == 0; ```
This expression would be more readable with extra parentheses: ``` a = ((b % 4 == 0) && (b % 100 != 0)) || (b % 400 == 0); ``` It is a test for leap year in the Gregorian calendar: bis a leap year if it is a multiple of4, except if it is a multiple of100, or if it is a multiple of400. As as example:2016is a leap year,2000was too, but1900was not and2100will not be a leap year. The||and&&operators are shortcut logical operators, for respectively OR and AND conditions. The expression is equivalent to this: ``` if (b % 4 == 0) { if (b % 100 != 0) { a = 1; } else { a = 0; } } else { if (b % 400 == 0) { a = 1; } else { a = 0; } } ```
``` static int i = 5; static int j = i; int main() { return 0; } ``` I am initializing the static variable by another static variable which is declared before that but also I am getting variable. Please tell me why this is error.
You cannot initializejwithi, because at compile time, compiler will not know the value ofi.To assign the valuej = i, the code need to be executed at run time. When initialize the global or static in C, the compiler and linker need to work together to create the layout of memory. Compiler will give the value and linker need to give the address of the variable. The below code will work: ``` static int i = 5; static int j; int main() { j=i; return 0; } ```
I have the following struct in C: ``` struct m{ unit32_t *p; // array of uint32_t }; ``` And the following function: ``` void print(struct *m); ``` How can I call this method with JNA and represent the structure in Java?
Nominally you'd do this: ``` public interface MyLib extends Library { class MyStruct extends Structure { public Pointer p; protected List getFieldOrder() { return Arrays.asList("p"); } } void print(MyStruct s); } MyLib lib = Native.loadLibrary("mylib", MyLib.class); MyStruct s = new MyStruct(); s.p = new Memory(length * 4); lib.print(s); ```
I was studying logic gates when I came to know that each logic gate was already defined inC. For example, for theANDlogic gate, the symbol is&. ForOR, it is|. But I could not find a symbol for theMUXchip. So, if there is a symbol forMUX, could someone tell me? If there isn't, could someone tell me how to replicate aMUXchip in C?
Closest is the conditional operator:?: eg: ``` x ? b : a ``` ifxis0you getaif it's1(or anything else) you getb This operator works on entire values, like||&&==and!do. It does not operate on bits as^~&and|do. There is no direct equivalent for a multi-input mux. but you can fake one using an anonymous array, eg: ``` ((int[]){a,b,c,d,})[x] ``` but many people frown on constructions of that form. if you need a bitwise mux you'll need to build it from the bitwise operators eg: ``` a ^ (( b ^ a ) & x) ```
I'm copying a string but for some reason the string is being copied twice. ``` bool check(const char* word) { // copy the word char *copy = malloc(sizeof(word)); strcpy(copy, word); printf("word %s\n", word); printf("copy %s\n", copy); return false; } ``` The output of this function is ``` word myWord copy myWord myWord ``` If i remove the '\n' character in the printf for copy, the output changes to ``` word myWord copy myWordmyWord ``` I've tried walking through this code with a debugger but the debugger is showing the value of copy to be "myWord" Does anyone have an idea what may be happening here?
you need to allocatestrlen(word) + 1bytes.sizeof(word)returns the number of bytes for storing a pointer.
I want to set a global reference of an int array, in C language, but I want to initialize it inside main function (actually the user is going to declare its size). Anyone knows how is this done? Thanks in advance!
Declare a pointer to an int as a global variable and initialize it in main using malloc. ``` /* outside any function, so it's a global variable: */ int *array; size_t array_size; /* inside main(): */ array_size = user_defined_size; array = malloc( sizeof(int)*array_size); if ( array == NULL) { /* exit - memory allocation failed. */ } /* do stuff with array */ free(array); ``` If you need to access the global variable from another module (source file), declare it there again using ``` extern int *array; extern size_t array_size; ``` or, preferably, declare themexternin a header file included in any source file that uses the array, including the source where they are defined (to ensure type consistency).
I wrote two new system calls and add them to the xv6 OS kernel. So using one system call I can save process state and using the other one I can reload the previous state and continue. theproblemis in thereloading section. is it enough to reload just the context of the process ? (i mean thestruct contextwhich contains some CPU register)
No. The process may have open files and pipes inproc->ofile, which you need to save/load. Note also that by the time you re-load a process, itsparentmay no longer exist.You'll really want to make sure your process isn't floating around without a real parent, or you'll be in for some fun bugs.
I am confused as to why my program keeps on crashing. I am usingCode Blocks, an open source IDE. Here is the code: ``` int main() { int age; char gender; printf("What is your age?\n"); scanf(" %d", age); printf("What is your gender? \(m/f)\n"); scanf(" %c", gender); if (age>=18){ printf("Access granted! Please proceed\n"); if (gender == 'm'){ printf("What's up dude?"); }; if (gender == 'f'){ printf("How's it going dudette?"); }; }; if (age<18){ printf("Access denied. Please get on with your life.\n"); }; return 0; } ```
scanf requires a pointer to the variable you're setting. So, you need to do: ``` scanf(" %d", &age); ``` and similar for gender
One of the arguments tommapisflags. To what extent is it possible to reconstruct which flags were used with the information in/proc/self/maps?
See details on/proc/self/mapsinthis question. Some ideas (actually not a full answer): MAP_PRIVATEandMAP_SHAREDflags may be determined from permissions columnMAP_ANONYMOUSis determined by empty pathsome flags (probablyMAP_HUGETLB,MAP_LOCKED) may be determined from/proc/self/smapssome flags likeMAP_FIXED(probablyMAP_32BIT,MAP_UNINITIALIZED) are most likely not saved anywhere aftermmap()returnssome flags (MAP_NONBLOCK,MAP_NORESERVE,MAP_POPULATE) are likely to be stored somewhere, but I don't think they're accessible through/proc HTH
I have this code: ``` char str [80]; int i; printf ("Enter your family name: "); scanf ("%79s",str); printf ("Enter your age: "); scanf ("%d",&i); ``` Why isscanf()of astringsaved tostrwhile for theintit is being sent to thepointer of i?
scanfneeds to be passed the address of a variable in order to modify it. When passing an array (achararray, in this case) to a function, the array decays into a pointer to the first element. So passingstrfor the%sspecifier is functionally the same as passing in&str[0]. This also works for achar *which points to dynamically allocated memory: ``` char *str = malloc(80); scanf ("%79s",str); ```
I'm attempting to capture'\\'with Python regex via the re module. I have attempted to do this using: ``` back = re.compile(r"'\\'") print back.findall(line) ``` Wherelineis:char = '\\'; But this doesn't capture anything. I also tried: ``` back = re.compile("'\\\\'") print back.findall(line) ``` To no avail. What's wrong with my regex?
You need to escape the backslash: ``` back = re.compile(r"'\\\\'") ``` Code: ``` >>> back = re.compile(r"'\\\\'") >>> line = r"char = '\\';" >>> print back.findall(line) ["'\\\\'"] ```
I want to read a string and 4 integers then display what I read then read again a string and 4 integers. I want to keep doing this until i get to the end of file ( hitting ctrl + D). For example : tennis 4 2 3 2 (hit enter) (the output) helloworld 2 8 7 4 (hit enter) (the output) Here is what I tried to do : ``` #include <stdio.h> int main() { char name[30]; int won = 0; int lost = 0; int tie = 0; int streak = 0; int ch; while((ch = getchar()) != EOF) { scanf("%s %d %d %d %d",name,&won,&lost,&tie,&streak); printf("%s%d%d%d%d",name,won,lost,tie,streak); } return 0; } ```
``` while(scanf("%29s%d%d%d%d",name,&won,&lost,&tie,&streak) == 5) printf("%s%d%d%d%d",name,won,lost,tie,streak); ``` Fromman -s3 scanf: These functions return the number of input items successfully matched and assigned
I wrote two new system calls and add them to the xv6 OS kernel. So using one system call I can save process state and using the other one I can reload the previous state and continue. theproblemis in thereloading section. is it enough to reload just the context of the process ? (i mean thestruct contextwhich contains some CPU register)
No. The process may have open files and pipes inproc->ofile, which you need to save/load. Note also that by the time you re-load a process, itsparentmay no longer exist.You'll really want to make sure your process isn't floating around without a real parent, or you'll be in for some fun bugs.
I am confused as to why my program keeps on crashing. I am usingCode Blocks, an open source IDE. Here is the code: ``` int main() { int age; char gender; printf("What is your age?\n"); scanf(" %d", age); printf("What is your gender? \(m/f)\n"); scanf(" %c", gender); if (age>=18){ printf("Access granted! Please proceed\n"); if (gender == 'm'){ printf("What's up dude?"); }; if (gender == 'f'){ printf("How's it going dudette?"); }; }; if (age<18){ printf("Access denied. Please get on with your life.\n"); }; return 0; } ```
scanf requires a pointer to the variable you're setting. So, you need to do: ``` scanf(" %d", &age); ``` and similar for gender
One of the arguments tommapisflags. To what extent is it possible to reconstruct which flags were used with the information in/proc/self/maps?
See details on/proc/self/mapsinthis question. Some ideas (actually not a full answer): MAP_PRIVATEandMAP_SHAREDflags may be determined from permissions columnMAP_ANONYMOUSis determined by empty pathsome flags (probablyMAP_HUGETLB,MAP_LOCKED) may be determined from/proc/self/smapssome flags likeMAP_FIXED(probablyMAP_32BIT,MAP_UNINITIALIZED) are most likely not saved anywhere aftermmap()returnssome flags (MAP_NONBLOCK,MAP_NORESERVE,MAP_POPULATE) are likely to be stored somewhere, but I don't think they're accessible through/proc HTH
I have this code: ``` char str [80]; int i; printf ("Enter your family name: "); scanf ("%79s",str); printf ("Enter your age: "); scanf ("%d",&i); ``` Why isscanf()of astringsaved tostrwhile for theintit is being sent to thepointer of i?
scanfneeds to be passed the address of a variable in order to modify it. When passing an array (achararray, in this case) to a function, the array decays into a pointer to the first element. So passingstrfor the%sspecifier is functionally the same as passing in&str[0]. This also works for achar *which points to dynamically allocated memory: ``` char *str = malloc(80); scanf ("%79s",str); ```
I'm attempting to capture'\\'with Python regex via the re module. I have attempted to do this using: ``` back = re.compile(r"'\\'") print back.findall(line) ``` Wherelineis:char = '\\'; But this doesn't capture anything. I also tried: ``` back = re.compile("'\\\\'") print back.findall(line) ``` To no avail. What's wrong with my regex?
You need to escape the backslash: ``` back = re.compile(r"'\\\\'") ``` Code: ``` >>> back = re.compile(r"'\\\\'") >>> line = r"char = '\\';" >>> print back.findall(line) ["'\\\\'"] ```
I want to read a string and 4 integers then display what I read then read again a string and 4 integers. I want to keep doing this until i get to the end of file ( hitting ctrl + D). For example : tennis 4 2 3 2 (hit enter) (the output) helloworld 2 8 7 4 (hit enter) (the output) Here is what I tried to do : ``` #include <stdio.h> int main() { char name[30]; int won = 0; int lost = 0; int tie = 0; int streak = 0; int ch; while((ch = getchar()) != EOF) { scanf("%s %d %d %d %d",name,&won,&lost,&tie,&streak); printf("%s%d%d%d%d",name,won,lost,tie,streak); } return 0; } ```
``` while(scanf("%29s%d%d%d%d",name,&won,&lost,&tie,&streak) == 5) printf("%s%d%d%d%d",name,won,lost,tie,streak); ``` Fromman -s3 scanf: These functions return the number of input items successfully matched and assigned
I am confused as to why my program keeps on crashing. I am usingCode Blocks, an open source IDE. Here is the code: ``` int main() { int age; char gender; printf("What is your age?\n"); scanf(" %d", age); printf("What is your gender? \(m/f)\n"); scanf(" %c", gender); if (age>=18){ printf("Access granted! Please proceed\n"); if (gender == 'm'){ printf("What's up dude?"); }; if (gender == 'f'){ printf("How's it going dudette?"); }; }; if (age<18){ printf("Access denied. Please get on with your life.\n"); }; return 0; } ```
scanf requires a pointer to the variable you're setting. So, you need to do: ``` scanf(" %d", &age); ``` and similar for gender
One of the arguments tommapisflags. To what extent is it possible to reconstruct which flags were used with the information in/proc/self/maps?
See details on/proc/self/mapsinthis question. Some ideas (actually not a full answer): MAP_PRIVATEandMAP_SHAREDflags may be determined from permissions columnMAP_ANONYMOUSis determined by empty pathsome flags (probablyMAP_HUGETLB,MAP_LOCKED) may be determined from/proc/self/smapssome flags likeMAP_FIXED(probablyMAP_32BIT,MAP_UNINITIALIZED) are most likely not saved anywhere aftermmap()returnssome flags (MAP_NONBLOCK,MAP_NORESERVE,MAP_POPULATE) are likely to be stored somewhere, but I don't think they're accessible through/proc HTH
I have this code: ``` char str [80]; int i; printf ("Enter your family name: "); scanf ("%79s",str); printf ("Enter your age: "); scanf ("%d",&i); ``` Why isscanf()of astringsaved tostrwhile for theintit is being sent to thepointer of i?
scanfneeds to be passed the address of a variable in order to modify it. When passing an array (achararray, in this case) to a function, the array decays into a pointer to the first element. So passingstrfor the%sspecifier is functionally the same as passing in&str[0]. This also works for achar *which points to dynamically allocated memory: ``` char *str = malloc(80); scanf ("%79s",str); ```
I'm attempting to capture'\\'with Python regex via the re module. I have attempted to do this using: ``` back = re.compile(r"'\\'") print back.findall(line) ``` Wherelineis:char = '\\'; But this doesn't capture anything. I also tried: ``` back = re.compile("'\\\\'") print back.findall(line) ``` To no avail. What's wrong with my regex?
You need to escape the backslash: ``` back = re.compile(r"'\\\\'") ``` Code: ``` >>> back = re.compile(r"'\\\\'") >>> line = r"char = '\\';" >>> print back.findall(line) ["'\\\\'"] ```
I want to read a string and 4 integers then display what I read then read again a string and 4 integers. I want to keep doing this until i get to the end of file ( hitting ctrl + D). For example : tennis 4 2 3 2 (hit enter) (the output) helloworld 2 8 7 4 (hit enter) (the output) Here is what I tried to do : ``` #include <stdio.h> int main() { char name[30]; int won = 0; int lost = 0; int tie = 0; int streak = 0; int ch; while((ch = getchar()) != EOF) { scanf("%s %d %d %d %d",name,&won,&lost,&tie,&streak); printf("%s%d%d%d%d",name,won,lost,tie,streak); } return 0; } ```
``` while(scanf("%29s%d%d%d%d",name,&won,&lost,&tie,&streak) == 5) printf("%s%d%d%d%d",name,won,lost,tie,streak); ``` Fromman -s3 scanf: These functions return the number of input items successfully matched and assigned
Suppose I've a portability problem caused by this functionfoothat can take one or two parameters depending on the system: ``` #include "config.h" #ifdef FOO_ONEPARAM #define FOO(a) foo(a) #else #define FOO(a) foo(a,b) #endif ``` How do I set properlyFOO_ONEPARAMafter disconvering it withAC_SEARCH_LIBS?
You could check theGNU Autoconf Archiveto see if someone has written a macro forfooalready. If not, you can use the method used bythis macroat the GNU Autoconf Archive to write your own, which is superficially similar to what you're already doing. There's probably several macros at the archive that do something like this (for old functions mostly), this was just the first one I ran across.
I am trying to save how many empty elements there are in an array. This is what I have done so far but it prints out that all lines are "not empty" which is wrong. How can I do this? ``` char arr[10][50]={NULL}; int lines; //inserting values to arr for(int i=0;i<10;i++){ if(arr[i] == NULL){ lines++; printf("empty"); } else printf("not empty"); } ```
When you doarr[i] == NULLthenarr[i]decays to a pointer to the first element of the array inarr[i](i.e.&arr[i][0]), and that pointer willneverbeNULL. I suspect you want e.g. something likearr[i][0] == '\0'.
Using visual studio 2013, creating a standard win32 console application, mktime returns negative(-1) regardless of params passed. Are there any reasons this code should fail this way? I can't tell that any combination of tm params passed makes any difference. ``` #include "stdafx.h" #include <time.h> int _tmain(int argc, _TCHAR* argv[]) { struct tm stm; stm.tm_sec = 27; stm.tm_min = 5; stm.tm_hour = 18; stm.tm_mday = 2; stm.tm_mon = 1; stm.tm_year = 2015; stm.tm_wday = 0; stm.tm_yday = 0; printf("%lld\n", mktime(&stm));//prints -1 return 0; } ```
Your value2015forstm.tm_yearis invalid. Subtract1900es explained inMSDN. Note that the month values start with 0 for January.
This question already has answers here:Set variable text column width in printf(2 answers)Closed7 years ago. I know that I could useprintf(%Nd, foo)if N is constant and I know itBut the problem is that N is in variable and calculated in program I could do it with combiningsprintfandprintf: ``` sprintf(formatstr, "%%%dd", N); printf(formatstr, foo); ``` But is there any cleaner way?
You can put a*in place of the field width. This means the next parameter will specify the width: ``` printf("%0*d", size, foo); ```
Suppose I've a portability problem caused by this functionfoothat can take one or two parameters depending on the system: ``` #include "config.h" #ifdef FOO_ONEPARAM #define FOO(a) foo(a) #else #define FOO(a) foo(a,b) #endif ``` How do I set properlyFOO_ONEPARAMafter disconvering it withAC_SEARCH_LIBS?
You could check theGNU Autoconf Archiveto see if someone has written a macro forfooalready. If not, you can use the method used bythis macroat the GNU Autoconf Archive to write your own, which is superficially similar to what you're already doing. There's probably several macros at the archive that do something like this (for old functions mostly), this was just the first one I ran across.
I am trying to save how many empty elements there are in an array. This is what I have done so far but it prints out that all lines are "not empty" which is wrong. How can I do this? ``` char arr[10][50]={NULL}; int lines; //inserting values to arr for(int i=0;i<10;i++){ if(arr[i] == NULL){ lines++; printf("empty"); } else printf("not empty"); } ```
When you doarr[i] == NULLthenarr[i]decays to a pointer to the first element of the array inarr[i](i.e.&arr[i][0]), and that pointer willneverbeNULL. I suspect you want e.g. something likearr[i][0] == '\0'.
Using visual studio 2013, creating a standard win32 console application, mktime returns negative(-1) regardless of params passed. Are there any reasons this code should fail this way? I can't tell that any combination of tm params passed makes any difference. ``` #include "stdafx.h" #include <time.h> int _tmain(int argc, _TCHAR* argv[]) { struct tm stm; stm.tm_sec = 27; stm.tm_min = 5; stm.tm_hour = 18; stm.tm_mday = 2; stm.tm_mon = 1; stm.tm_year = 2015; stm.tm_wday = 0; stm.tm_yday = 0; printf("%lld\n", mktime(&stm));//prints -1 return 0; } ```
Your value2015forstm.tm_yearis invalid. Subtract1900es explained inMSDN. Note that the month values start with 0 for January.
This question already has answers here:Set variable text column width in printf(2 answers)Closed7 years ago. I know that I could useprintf(%Nd, foo)if N is constant and I know itBut the problem is that N is in variable and calculated in program I could do it with combiningsprintfandprintf: ``` sprintf(formatstr, "%%%dd", N); printf(formatstr, foo); ``` But is there any cleaner way?
You can put a*in place of the field width. This means the next parameter will specify the width: ``` printf("%0*d", size, foo); ```
I came across this code line in C: ``` #define RUNDE(n) ( K ^= Q[n], y = K, K = F(K) ^ xR, xR = y ) ``` Is it valid to assign something to K multiple times? I thought it's invalid to change a variable more than one time in one statement.
Is it valid to assign something to K multiple times? That's perfectly valid C macro. A comma operator,is used here. Using,operator you can assign a value to a variable multiple times. e.g.K = 20, K = 30;This will assign30toKoverwriting the previous value of20. I thought it's invalid to change a variable more than one time in one statement. Yes it leads to undefined behavior if we try to modify a variable more than once in a same C statement but here first,is asequence point. So it's guaranteed that we will be modifying theKsecond time (K = 30) only when all the side effects of first assignment (K = 20) have taken place.
I am trying parse a c file and find all the variables that begin with "Apple_". I read the entire c file to a string and then use a regex to get all the variables. But I have a macro defined as: #define IAMMACRO(var,ext) var##ext so if I have ``` IAMAMACRO(Apple_,Variable) ``` I need to get the value Apple_Variable after the parsing and not Apple_. PS: I prefer an easy solution.
As as understand, you want : to read, then parse C (C++?) file ;to embed it in a software;to have aneasysolution :) So, solutions to use gcc galaxy is rather complicated, and heavy (in fact, you dont care about compiling). Advice : dont try to parse yourself. It is a big job ! Solution:justparse. Use a library to do that. Use ANTLR4 (not so easy), with an already-made grammar for C/C++: ANTLR4:http://www.antlr.org/ Grammar for C++:https://github.com/antlr/antlr4-cpp see also that:Antlr4 C++ target hope it helps !
Which is better (in both performance and best practice) for printingonlya newline: putchar('\n')orputs("") From what I understand,putcharoutputs a single character andputsoutputs a string of characters.Forget aboutprintf. I'm inclined to useputsbecause it's shorter, but doing("")justfeelswrong. Which is faster and better?
Any speed difference between them is going to be insignificant, butputcharis probably faster because it takes a single char argument. Far more importantly,putchar('\n')issaying what you mean, whileputs("")isn't.
I think the title is pretty self explanatory but basically what I'm saying is that, if I have the following instruction: ``` a = (char) b; ``` knowing thata's type ischarandb's isunsigned char, can that instruction result in makingaandbhave different binary representations?
The typecharcan be either signed or unsigned. Char types have no padding, so all bits are value bits. Ifcharis unsigned, then the value bits ofawill be the same as those ofb.Ifcharis signed, then...if the value ofbis representable bychar, the common value bits ofaandbwill the same.otherwise, the conversion from unrepresentableunsigned charvalue tocharresults in animplementation-definedresult.
I am trying parse a c file and find all the variables that begin with "Apple_". I read the entire c file to a string and then use a regex to get all the variables. But I have a macro defined as: #define IAMMACRO(var,ext) var##ext so if I have ``` IAMAMACRO(Apple_,Variable) ``` I need to get the value Apple_Variable after the parsing and not Apple_. PS: I prefer an easy solution.
As as understand, you want : to read, then parse C (C++?) file ;to embed it in a software;to have aneasysolution :) So, solutions to use gcc galaxy is rather complicated, and heavy (in fact, you dont care about compiling). Advice : dont try to parse yourself. It is a big job ! Solution:justparse. Use a library to do that. Use ANTLR4 (not so easy), with an already-made grammar for C/C++: ANTLR4:http://www.antlr.org/ Grammar for C++:https://github.com/antlr/antlr4-cpp see also that:Antlr4 C++ target hope it helps !
Which is better (in both performance and best practice) for printingonlya newline: putchar('\n')orputs("") From what I understand,putcharoutputs a single character andputsoutputs a string of characters.Forget aboutprintf. I'm inclined to useputsbecause it's shorter, but doing("")justfeelswrong. Which is faster and better?
Any speed difference between them is going to be insignificant, butputcharis probably faster because it takes a single char argument. Far more importantly,putchar('\n')issaying what you mean, whileputs("")isn't.
I think the title is pretty self explanatory but basically what I'm saying is that, if I have the following instruction: ``` a = (char) b; ``` knowing thata's type ischarandb's isunsigned char, can that instruction result in makingaandbhave different binary representations?
The typecharcan be either signed or unsigned. Char types have no padding, so all bits are value bits. Ifcharis unsigned, then the value bits ofawill be the same as those ofb.Ifcharis signed, then...if the value ofbis representable bychar, the common value bits ofaandbwill the same.otherwise, the conversion from unrepresentableunsigned charvalue tocharresults in animplementation-definedresult.
I am experimenting with a code, I have looked through the other posts, but couldn't figure it out, could you help me out on why I am getting: ``` error: expected expression before ';' token char passwd[] = PASSWORD; ``` ========================= ``` #include <stdio.h> #include <string.h> #define SIZE 100 #define PASSWORD ******** int main() { int count = 0; char buff[SIZE] = " "; char passwd[] = PASSWORD; ... ```
#definedirective would define a label for some primitive value. This implies your code will be interpreted aschar passwd[]=********;in compile time. You probably need quotes around the **: ``` #define PASSWORD "********" ```
I'm unsure as to the complexity of the following block of C: ``` int i = 0, j = 1; for ( i = 0; i < n * n; i += j ) { O1(); j += 2; } ``` where O1 is a function that obviously takes constant time to execute. Now, I am aware that loops whose counter gets increased by a constant amount every iteration generally have a complexity ofO(sqrt(n)), but is this the case here as well? Or is itO(sqrt(n^2)), that isO(n)? Thanks
I am aware that loops whose counter gets increased by a constant amount every iteration generally have a complexity of O(sqrt(n)) That's false. A loop whose counter gets increased by a constant amount every iteration is O(N). A loop whose counter increases by an amount that increases linearly on each iteration is O(sqrt(N)). In this case,Nhere isn * n, as that's what your loop is looping until, so that simple replacement tells you that, yes, the operation is O(sqrt(n^2)) or O(n).
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 I have a problem, I have a file with some number delimited by "". For example "125" etc. An example of the file is: ``` 10.0.0.0 11.0.0.0 "1200" 10.0.0.1 11.0.0.0.1 "200" 11.0.0.1 11.0.0.2 "320" ``` I useAWKfor take the data but my problem is that I have to take only the integer value of the third column without "" because after I need to have some calculation with this numbers. The solution is good also inClanguage. Someone can help me? Thanks
In awk, you'll have to strip off the quotes manually ``` $ echo '"2134"' | awk '{gsub(/(^")|("$)/,"",$1); print $1+2}' 2136 ``` Obviously, this is not a C answer.
I wish to use a block size that is padded to the nearest 32 so my function below I thought would be 36/32 = 1.125, ceil = 2, 2*32 = 64 however somewhere from converting from double to int I am getting the answer of 32. ``` double dbl; int block_size; dbl = ceil(36/32); block_size = (int)dbl*32; // equals 32 ```
When you callceil(36/32)you're dividing two integers, so you get an integer as a result (1 in this case). Try dividing doubles:ceil(36.0/32.0).
I created windows console program project in visual studio, and made two c language files. Both has same source: ``` #include<stdio.h> int main() { printf("hello"); } ``` When I try to compile, compiler screams about having twomain()s. See below: I can't understand. I thought two files in one project works separately. Am I wrong?
Yes, you are wrong. IIRC, the wholeprojectis compiled and then linked to form a single executable. In a single executable, there can be only onemain()function.
I've seen structs declared two different ways. ``` typedef struct _myStruct { ... } myStruct; ``` and ``` typedef struct myStruct { ... } myStruct; ``` Is there a reason for the leading underscore or is this just a stylistic thing? If there is not a difference, is one of these preferred over the other?
The former was used long ago, when some compiler(s) didn't allow the tag and the typedef to use the same identifier. The latter is currently preferred, and in fact, identifiers that start with an underscore are discouraged.
This question already has answers here:What is the behavior of integer division?(6 answers)Closed7 years ago. ``` #include <stdio.h> int main(int argc, const char * argv[]) { int a = 10; int b = 20; double result = a / b; printf("%d divided by %d makes %f\n", a, b, result); return 0; } ``` Expecting that the%fwould return 0.500000, I ran the code and it turned out to be 0.000000. Is there a reason that theresultvariable is returning a zero value?
Because it's performing integer devision sinceaandbareints, try this ``` double result = (float) a / (float) b; ```
Which of the following methods is a more correct way to initialize a variable? ``` int x = 0; int x = NULL; ``` What about the pointers? I have been told discordant things aboutNULL, like : "NULLis best for initializing pointers" or "Don't useNULLbut 0 to initialize a variable" and so on... Now, I read on the internet thatNULLis equal to 0 and I tested that myself. So what's the point? Why are some people saying that using NULL isn't a good choice? Is there something that I'm missing?
NULLis a pointer constant. You use this to initialize a pointer to a value that says it doesn't point to anything. On most C implementations, it is defined as: ``` #define NULL ((void *)0) ``` But there's no guarantee of that.
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.Closed7 years ago.Improve this question A feasible way to achieve a suitable time delay is to use busy-waiting, however what are the advantages and disadvantages of using a busy-waiting or timer interrupts approach programming?
There are probably many, I will try to address what seems most important to me. Advantages of busy-waiting: The execution flow is usually easier to comprehend and thus less error prone.Timing can be determined more accurately in some cases Disadvantages: No other code (except perhaps other interrupt routines) can be executed.CPU-time is wasted: If no other work must be processed it is still more efficient to set some powersaving-state and let a timer interrupt wake it up in time.
This question already has answers here:Reading the Device Status Report ANSI escape sequence reply(4 answers)Closed7 years ago. I need to get my (Y, X) position of my terminal's cursor with the termcaps in C. Withioctl()i get the size of my terminal screen, but i still need to get where my cursor is. I found this : CSI 6 n DSR – Device Status Report Reports the cursor position to the application as (as though typed at the keyboard) ESC[n;mR, where n is the row and m is the column. (May not work on MS-DOS.) But i have no idea how to use it in C ...
You write the command sequence (<ESC>[6n) to the terminal using normal output tostdout. Then you read the response using normal input fromstdin. You need to parse the "reply" to pick out the position.
Let's say I have to parse some phone numbers that can have different delimiters. Example: 01/555555 01/555-5555 Can I usestrtok()in c and give a regex as a delimiter parameter that would include all the different possible delimiters?
No, it does not supportregex. Read the documentation before asking. On the other hand, that's precisely how it works so againRead the documentation, i.e. You give it all the possible delimiters. Check it here ``` #include <stdio.h> #include <string.h> int main(void) { char example[] = "exa$mple@str#ing"; char *token; char *pointer; pointer = example; token = strtok(pointer, "@#$"); if (token == NULL) return -1; do { fprintf(stdout, "%s\n", token); pointer = NULL; } while ((token = strtok(NULL, "@#$")) != NULL); } ```
I have a filegame.hwhich has this declaration ``` typedef struct Enemy { ... }Enemy; ``` And a function ``` void moveEnemy(Level* l, Enemy* enemy){ ... } ``` Levelis declared onlevels.h, so ingame.hI have: ``` #include "levels.h" ``` Everything was perfect, until I had to useEnemyinlevels.h. So, inlevels.hI added: ``` #include "game.h" ``` And now I get a compilation error: ``` game.h:34:2: error: unknown type name ‘Level’ Level* level; ^ ``` I have include guards on both .h I don't know why I can't have on file including another. What can I do?
Just add a forward declaration, like this ingame.hbefore the function, ``` typedef struct Level Level; ``` since it's just a pointer toLevelthis will do it.
I want to use the functionstrftime()from<ctime>to print the time in the ISO 8601 UTC format, e.g.2016-01-12T10:37:20Z. According to the standardcplusplus, the format string%FT%TZproduces the same as"%Y-%m-%dT%H:%M:%SZ", but Visual Studio 2010 does not know the format specifiers %F and %T. Why is that?They seem to have forgotten them?!
Those features were introduced to standardC in C99, and toC++ in C++11. It seems that Visual Studio 2010 supports neither of those standards.
Is there a way to start handling a case, and in themiddle(not end) of it to move on to run the 'default'. I saw that I can drop the 'break', but it continues to the next cases just after ending the whole current case. Example: ``` switch( X ) { case 'A': // Start this code if (expression){ // Go to execute 'default' } // Don't run this if the expression is true case 'B': // code.. default : // code.. } ``` (Looking for a solution other than making the 'default' a function and calling it from the case)
You can use a label: ``` goto default2; ``` if you put a: ``` default2: ``` next to the default
``` int a; scanf("%d",a); typedef struct mylist { int info[a]; struct mylist *link; } Node; ``` this is my very simple struct and variable 'a' that don't work. The thing which I want my program to do is to read input from the user and insert the digit into the struct (the user can determine the size of the array), however, I don't know how to do it since I get an error: "variably modified ‘info’ at file scope". I want to know whether it is possible to do this in a simple way.
When you usescanfinto an integer you must pass a pointer. You may want to check the documentation. ``` scanf("%d", &a); ``` As far as using a variable to allocate data, you can do it, but you will want to usemallocmost likely after defining your structure as a type.
first of all i would like to ask you how to create this process tree listed below with using only fork() function. ``` |____1____ |___2__ | |_4_ | |_3_ | | | | | #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main() { if (fork()) { ``` The thing is I don't know what to do next and how it works.
Let's try that with a bit more whitespace and some placeholder comments for you to fill in: ``` /* initial process */ if (fork()) { /* process ? */ if (fork()) { /* process ? */ if (fork()) { /* process ? */ } else { /* process ? */ } } else { /* process ? */ } } else { /* process ? */ if (fork()) { /* process ? */ } else { /* process ? */ } } ```
Say if you have the following IP address: ``` 192.168.0.255 ``` How can I store that human readable IP address into astruct in_addr? I'm brand new to network programming in C at this low level, so any help would be greatly appreciated.
You can do ``` struct in_addr p; inet_aton("192.168.0.255", &p.s_addr); ```
Related tothis question--- I'm debugging some code that unlocks a mutex twice and I'm trying to figure out exactly when it happens. I'm getting stack traces out of Helgrind, but I'd like the program to crash immediately when it performs the bad unlock. I know the behavior of unlocking an already-unlocked mutex is undefined, and so nasal demons are an acceptable implementation --- I certainly can't force nasal demons to crash. But given the pthreads implementation in recent versions of glibc, is there a way to get this behavior reasonably reliably?
Instead of obtaining a crash, what you can do is check the return value ofpthread_mutex_unlock, and use an error-checking mutex (PTHREAD_MUTEX_ERRORCHECKmutex type). If you detect an error, callabort()or whatever.
Why is it that the following: ``` #include <stdio.h> int main(int argc, char *argv[]) { char array[3] = {'1', '2', '3'}; printf("%s\n", array); return 0; } ``` produces1238À§Wˇ("123" + some random chars) as expected, while the same code with: int main(void) instead ofargc,argvproduces:123(despite there being no room for the null byte). How is it that the lack of room for a null byte inarraywithvoiddoesn't seem to matter?
You're not providing the end-of-string (EOS) zero byte, soprintfkeeps going until it [just happens] to find one (i.e. the garbage characters). Any of the following would work: ``` char array[4] = { '1', '2', '3', '\0' }; char array[4] = { '1', '2', '3' }; char array[4] = "123"; char array[] = { '1', '2', '3', '\0' }; char array[] = "123"; char *array = "123"; ```
If a thread suffers a major fault while trying to read from an address, and the data must be swapped in from "disk", does Linux take advantage of that to run another waiting thread, if there is one? From what I've read online, the answer is yes. But I haven't seen anything conclusive.
That depends on the scheduler you use. In general, the answer isyes,unless the disk operation is sufficiently fast or unless the kernel has another reason not to swap in a different process.
For example, we have 1 CPU with 8 Cores. How many maximum different CPU-Cores can be used to processing of one IP-packet when it going over Eth0->TCP/IP->App (exclude processing in Application)? For example, could it be 3 CPU-Cores: Process hardware interruptProcess checksum calculationProcess copy kernel-space -> user-space (whose pointer has been sent to the socket) This is very important for the performance, as each transfer of data between the cores is very expensive.
Generally speaking you'll handle the interrupt on one core, have a chance that the actual kernel work involved in processing it will happen on a different core, and finally hand it off to an application running on a third core. On some OSs you can set process affinity as well as interrupt handler affinity to avoid bouncing your data around.
Is there a way to start handling a case, and in themiddle(not end) of it to move on to run the 'default'. I saw that I can drop the 'break', but it continues to the next cases just after ending the whole current case. Example: ``` switch( X ) { case 'A': // Start this code if (expression){ // Go to execute 'default' } // Don't run this if the expression is true case 'B': // code.. default : // code.. } ``` (Looking for a solution other than making the 'default' a function and calling it from the case)
You can use a label: ``` goto default2; ``` if you put a: ``` default2: ``` next to the default
``` int a; scanf("%d",a); typedef struct mylist { int info[a]; struct mylist *link; } Node; ``` this is my very simple struct and variable 'a' that don't work. The thing which I want my program to do is to read input from the user and insert the digit into the struct (the user can determine the size of the array), however, I don't know how to do it since I get an error: "variably modified ‘info’ at file scope". I want to know whether it is possible to do this in a simple way.
When you usescanfinto an integer you must pass a pointer. You may want to check the documentation. ``` scanf("%d", &a); ``` As far as using a variable to allocate data, you can do it, but you will want to usemallocmost likely after defining your structure as a type.
I Would like to know how I can do exponent function in this code part (that means how I can change ^ to something that works in c language)? ``` K = (S * (P/100/12)) / (1 - (1 + (P/100/12))^(-Y*12) ); ```
It's thepow()function frommath.h ``` K = (S * (P / 100 / 12)) / (1 - pow((1 + (P / 100 / 12)), (-Y * 12))); ```
I have to write a C program that uses arguments like this : App.exe -in file.txt I know something about argv and char *argc but..how do I use the argument with fopen?That i don't know!
[Note that this doesn't answer the question, but it do show how to use arguments] Learn about the arguments first, and how they are handled. Then you know how to use the arguments and pass a filename on to thefopen(or any other) function. Try this little program first: ``` #include <stdio.h> int main(int argc, char *argv[]) { printf("argc = %d\n", argc); for (size_t a = 0; i < argc; ++a) { printf("argv[%zu] = \"%s\"\n", a, argc[a]); } } ``` If you execute this program like ``` args.exe -in file.txt ``` the output should be ``` argc = 3 argv[0] = "args.exe" argv[1] = "-in" argv[2] = "file.txt" ```
given a function that takes two numbers: Mirror( num 1, num 2) how do I check if num2 is the mirror of number 1? IN C for example if num 1= 523 num2=325 return 1: it's its mirror otherwise returns 0 more examples num1=566 num2:566 returns false num1=500 num2=005 return true the length of the two numbers is unknown
You can compute the reverse and then compare the result with your other number. ``` int mirror(int n,int m) { int rev=0; while(n>0) { rev*=10; rev+=n%10; n/=10; } return rev==m ? 1 : 0; } ```
here is my code, I get "X Error of failed request: BadWindow (invalid Window parameter)" ``` xdo_t *xdo = xdo_new(":0"); XWindowAttributes attr; XClassHint classhint; Window window; XGetWindowAttributes(xdo->xdpy, window, &attr); if (XGetClassHint(xdo->xdpy, window, &classhint)) { classhint.res_name; } ```
I find the solution, as error message show"(invalid Window parameter)”, it means I should first get window, in my case 62914561 is google-chrome window id(I get it withxdotool search google-chrome), following code should work ``` #include <X11/Xutil.h> #include <xdo.h> int main(int argc, char **argv) { Display *display = XOpenDisplay(NULL); XWindowAttributes attr; XClassHint classhint; Window window = 62914561; XGetWindowAttributes(display, window, &attr); if (XGetClassHint(display, window, &classhint)) { classhint.res_name; } } ```
I'm writing a code like this ``` int reverse(int x) { long long res; ...... if(x>0&&res>INT_MAX||x<0&&res>INT_MAX+1){ return 0; } ...... } ``` It shows overflow,but when I add conversion to this it complies ``` int reverse(int x) { long long res; ...... if(x>0&&res>(unsigned long long)INT_MAX||x<0&&res>(unsigned long long)INT_MAX+1){ return 0; } ...... } ``` Can somebody please explain to me what is the problem?
INT_MAX+1is evaluated as an integer addition of twoints. Since the resultant is not with the range of values that can be represented as anint, you see the overflow. (unsigned long long)INT_MAX+1is evaluated as an integer addition of twounsigned long longs. Since both sides of the operator and the resultant are well within the range of values that can be represented as anunsigned long long, there is no overflow.
I'm working on a C grammar analysis program. While running C preprocessor, there are some libraries which check the environment and use#errorto stop compiling. How can I disable them, since I only need the preprocess step to finish?
Why do you want to disable them? They are outputting an error and stopping compilation for a reason. The only way I know to disable them is to modify the source code and remove them.
I have the following code: ``` #include <stdio.h> #include <curl/curl.h> int main() { printf("hello world\n"); url_global_init( CURL_GLOBAL_ALL ); CURL * myHandle; CURLcode result; myHandle = curl_easy_init(); curl_easy_setopt( myHandle, CURLOPT_URL, "http://localhost"); result = curl_easy_perform( myHandle ); curl_easy_cleanup( myHandle ); return 0; } ``` I try to compile with gcc source.c -lcurl but unfortunately I get: /tmp/ccIbuIzd.o: In functionmain': source.c:(.text+0xad): undefined reference tourl_global_init' collect2: error: ld returned 1 exit status
There is nourl_global_init()it's ``` curl_global_init(CURL_GLOBAL_DEFAULT); ``` And you also need acurl_global_cleanup()at the end of the program.
I tried something but Resus mainly not know how to read the file line by line to compare lines between them, I get the error segmentation fault ( core dumped ). This is my function for uniq -u command ``` void uniq_u() { // strcpy(file_name1,params[2]); FILE *file = fopen ( file_name1, "r" ); if ( file != NULL ) { fgets(prev, sizeof prev,file); while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */ { if(!strcmp(line, prev)) printf("%s", prev); else strcpy(prev,line); } fclose ( file ); } } ``` Thanks!
Please mention the declaration of "prev" and "line" variables. Regardless , I think reading this might solve your problem :Difference between char* and char[]
given a function that takes two numbers: Mirror( num 1, num 2) how do I check if num2 is the mirror of number 1? IN C for example if num 1= 523 num2=325 return 1: it's its mirror otherwise returns 0 more examples num1=566 num2:566 returns false num1=500 num2=005 return true the length of the two numbers is unknown
You can compute the reverse and then compare the result with your other number. ``` int mirror(int n,int m) { int rev=0; while(n>0) { rev*=10; rev+=n%10; n/=10; } return rev==m ? 1 : 0; } ```
here is my code, I get "X Error of failed request: BadWindow (invalid Window parameter)" ``` xdo_t *xdo = xdo_new(":0"); XWindowAttributes attr; XClassHint classhint; Window window; XGetWindowAttributes(xdo->xdpy, window, &attr); if (XGetClassHint(xdo->xdpy, window, &classhint)) { classhint.res_name; } ```
I find the solution, as error message show"(invalid Window parameter)”, it means I should first get window, in my case 62914561 is google-chrome window id(I get it withxdotool search google-chrome), following code should work ``` #include <X11/Xutil.h> #include <xdo.h> int main(int argc, char **argv) { Display *display = XOpenDisplay(NULL); XWindowAttributes attr; XClassHint classhint; Window window = 62914561; XGetWindowAttributes(display, window, &attr); if (XGetClassHint(display, window, &classhint)) { classhint.res_name; } } ```
I'm writing a code like this ``` int reverse(int x) { long long res; ...... if(x>0&&res>INT_MAX||x<0&&res>INT_MAX+1){ return 0; } ...... } ``` It shows overflow,but when I add conversion to this it complies ``` int reverse(int x) { long long res; ...... if(x>0&&res>(unsigned long long)INT_MAX||x<0&&res>(unsigned long long)INT_MAX+1){ return 0; } ...... } ``` Can somebody please explain to me what is the problem?
INT_MAX+1is evaluated as an integer addition of twoints. Since the resultant is not with the range of values that can be represented as anint, you see the overflow. (unsigned long long)INT_MAX+1is evaluated as an integer addition of twounsigned long longs. Since both sides of the operator and the resultant are well within the range of values that can be represented as anunsigned long long, there is no overflow.
I'm working on a C grammar analysis program. While running C preprocessor, there are some libraries which check the environment and use#errorto stop compiling. How can I disable them, since I only need the preprocess step to finish?
Why do you want to disable them? They are outputting an error and stopping compilation for a reason. The only way I know to disable them is to modify the source code and remove them.
I have the following code: ``` #include <stdio.h> #include <curl/curl.h> int main() { printf("hello world\n"); url_global_init( CURL_GLOBAL_ALL ); CURL * myHandle; CURLcode result; myHandle = curl_easy_init(); curl_easy_setopt( myHandle, CURLOPT_URL, "http://localhost"); result = curl_easy_perform( myHandle ); curl_easy_cleanup( myHandle ); return 0; } ``` I try to compile with gcc source.c -lcurl but unfortunately I get: /tmp/ccIbuIzd.o: In functionmain': source.c:(.text+0xad): undefined reference tourl_global_init' collect2: error: ld returned 1 exit status
There is nourl_global_init()it's ``` curl_global_init(CURL_GLOBAL_DEFAULT); ``` And you also need acurl_global_cleanup()at the end of the program.
I tried something but Resus mainly not know how to read the file line by line to compare lines between them, I get the error segmentation fault ( core dumped ). This is my function for uniq -u command ``` void uniq_u() { // strcpy(file_name1,params[2]); FILE *file = fopen ( file_name1, "r" ); if ( file != NULL ) { fgets(prev, sizeof prev,file); while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */ { if(!strcmp(line, prev)) printf("%s", prev); else strcpy(prev,line); } fclose ( file ); } } ``` Thanks!
Please mention the declaration of "prev" and "line" variables. Regardless , I think reading this might solve your problem :Difference between char* and char[]
Structs containing arrays in C51 are not allowed? After defining a simple structure in my C51 program, ``` struct RingBuffer { int zero; int size; int capacity; char data[10]; }; ``` I got error:..\SOURCE\MYRINGBUFFER.H(25): error C141: syntax error near '['. It is clear that error is on the line with a char array defined in the struct(no errors after commenting). Am I doing something wrong here? If not, is there anyway I can achieve what I'm attempting to do? EDIT: All the code. ``` #ifndef __MY_RING_BUFFER_H__ #define __MY_RING_BUFFER_H__ #include <stdio.h> #include <stdlib.h> #include <string.h> struct RingBuffer { int zero; int size; int capacity; char data[10]; }; #endif ```
I figured out what's wrong.datais a keyword in C51.
In my program, I have a global buffer string, say ``` char buffer[110]; ``` It reads from an adapter and stores strings yet to be proceeded. I have something like this: ``` while(...){ readfromAdapter(); copytoBuffer(); processAndRemoveSomeCharsFromBuffer(); } ``` Every time a part of the string is proceeded, I want it removed from the buffer. I searched about how to remove first few characters from strings in C, in most answers I they increase the pointer, in this casebuffer. However, this should cause overflow in this case. I have 2 methods in mind. One is every time I use up the space in buffer, I free the old space and allocate some new space for it. In this case, I'll change buffer from an char array to global char pointer. The other one is every time some chars are proceeded, I copy the oldbuffer+lentobuffer. How should I do it?
It seems that aring buffercan help you.
``` #include <stdio.h > void main (){ int a = 0, b = 1, c = 2; *(( a+1 == 1) ? & b : &a ) = a ? b : c; printf ("%d , %d, %d\n ", a, b , c ); } ``` Explanation: ``` *(& b ) = a ? b : c ; b = a ? b : c ; b = 0 ? 1 : 2 ; //problem is here b = 2 ``` I have doubt in 2nd last line of explanation that, how b = 0 condition goes wrong and it gives b = 2 . why not b = 1 ? Sorry in case anything i missed.
The ternary operator has higher precedence than the assignment operator. Due to that, ``` b = 0 ? 1 : 2 ; ``` is interpreted as: ``` b = (0 ? 1 : 2) ; ``` not as: ``` (b = 0) ? 1 : 2 ; ``` Seehttp://en.cppreference.com/w/c/language/operator_precedencefor further details on operator precedence in C.
I am trying to learn how to program a GTK application. I created my first application and here is the callback function: ``` void click_button2 (GtkToggleButton *tbutton, gpointer data) { gtk_main_quit (); } ``` And here is how my GTK project looks:https://i.stack.imgur.com/zCHGr.png After compiling with: ``` gcc -Wall -g -o testGlade test.cpkg-config --cflags --libs gtk+-3.0 gmodule-2.0 ``` The cal back does not seem to work. Nothing happens when I click the button.
Please add your source code of the test.c for further help. Try compiling with -rdynamic option. ``` gcc -Wall -g -o testGlade test.c pkg-config --cflags --libs gtk+-3.0 gmodule-2.0 -rdynamic ```
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.Closed7 years ago.Improve this question if I've a large number stored in 10 bytes of memory, how can I convert this number to string? like How do C %d converts number to string? I'm not looking for some library or function, I wan't to know how to convert large byte numbers to string, that is what i need to know.
You need to use some combinatory logic to do this. A straightforward way consist in converting your 10 bytes number into BCD representation first (Binary-coded decimal), then convert your BCD number into an ASCII string, which is quite simple. Have a look at this for example:https://en.wikipedia.org/wiki/Double_dabble
I am trying to learn how to program a GTK application. I created my first application and here is the callback function: ``` void click_button2 (GtkToggleButton *tbutton, gpointer data) { gtk_main_quit (); } ``` And here is how my GTK project looks:https://i.stack.imgur.com/zCHGr.png After compiling with: ``` gcc -Wall -g -o testGlade test.cpkg-config --cflags --libs gtk+-3.0 gmodule-2.0 ``` The cal back does not seem to work. Nothing happens when I click the button.
Please add your source code of the test.c for further help. Try compiling with -rdynamic option. ``` gcc -Wall -g -o testGlade test.c pkg-config --cflags --libs gtk+-3.0 gmodule-2.0 -rdynamic ```
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.Closed7 years ago.Improve this question if I've a large number stored in 10 bytes of memory, how can I convert this number to string? like How do C %d converts number to string? I'm not looking for some library or function, I wan't to know how to convert large byte numbers to string, that is what i need to know.
You need to use some combinatory logic to do this. A straightforward way consist in converting your 10 bytes number into BCD representation first (Binary-coded decimal), then convert your BCD number into an ASCII string, which is quite simple. Have a look at this for example:https://en.wikipedia.org/wiki/Double_dabble
When defining a variable in the following manner: ``` static register int a1 = 0; ``` we get the error: ``` error: multiple storage classes in declaration specifiers ``` Is there any fundamental reason for this error? Why can't a variable be both stored in a register, and also be initialized only at start up/first call?It is possible to attach the register storage class to a global variable.<- edit: not true
The standard does not allow use of more than one storage-class specifier in a declaration. From the C99 Standard: 6.7.1 Storage-class specifiers1storage-class-specifier:typedef extern static auto register2 At most, one storage-class specifier may be given in the declaration specifiers in a declaration.
The manual wasn't clear on the subject. if I tellfread()to read from file 1 item of1024bytes each time (in a loop) and the last block is ofsize < 1024, I know thatfread()will return0. But, is the buffer going to contain the remainder?
The Standards says: 7.21.8.1 The fread functionIf a partial element is read, its value is indeterminate. The element in this case is of size 1024 bytes and you read one element. The element, entire block of 1024 bytes, will have an indeterminate value. Reading that value could cause undefined behavior. And: The fread function returns the number of elements successfully read, which may be less than nmemb if a read error or end-of-file is encountered. If you get a return value of 0, then zero elements were successfully read, another indicator that the element wasn't read correctly, and should not be used, as mentioned before.
Is it possible to get a function to return an int or a char* depending on what happened when executed ? I've tried void but at the compilation I get a lot of warning Example ``` void int_char(char *str) { if (I 'm matching a condition in my string) return (str); else return (0); } ``` I hope I am clear enough. PS : I'm a beginner in C programming
The sane way to design such a function would be: ``` char* get_buffer (const char *str) { if (I'm matching a condition in my string) return buffer; else return NULL; } ``` (assuming buffer is not a local variable)
I tried copying string with char pointers, and the program gave me nothing and I have no idea... Please let me know problems of my code. ``` int main() { char *a = "helloworld.txt"; char *b = malloc( sizeof(char) * 20 ); while(*a!='\0') { *b++=*a++; } *b = '.'; b++; *b = '\0'; printf("string: %s\n", b); } ``` the result was: ``` string: ```
You need this: ``` int main() { char *a = "helloworld.txt"; char *b = malloc( sizeof(char) * 20 ); char *c = b; // save pointer to allocated memory while(*a!='\0') { *b++=*a++; } *b = '.'; b++; *b = '\0'; // b points to the end of the constructed // string now printf("string: %s\n", c); // use pointer saved before instead of b } ```
I have a functionf(unsigned char ** data);. Additionally, I have a pointer to an objectpObjwith anunsigned char* pbCertmember. Thus I'd like to perform an operation such as this: ``` f(pObj->&pbCert); ``` Unfortunately, I getmember identifier expectederror. I managed to tackle with the problem using such approach: ``` unsigned char* temp = pObj->pbCert; f(&temp); ``` However I'm curious, is there some clever notation trick do do this in only one line?
The&goes before the entire member-access expression:f(&pObj->pbCert). (In fact, your own solution withunsigned char* tempis incomplete! Callingf(&temp)would modifytemp, but wouldn't modifypObj->pbCert, unless you manually re-assign it withpObj->pbCert = temp;after callingf.)
I have been using Cython to compile my Python files into C files and then use MinGW to create an executable from the C file. Cython works fine, I can typecython test.pyxinto the command line and get a C file. The problem is when I attempt to compile an executable from the C file. If I typegcc test.cI get the following error: ``` test.c:4:20: fatal error: Python.h: No such file or directory #include "Python.h" ^ compilation terminated. ``` I would really appreciate some help. I am running windows 7 and python 3.5.
you probably don't have python-dev installed. Depending on your OS, you'd need to do something like this: ``` sudo apt-get install python-dev ``` Which is what you'd do on Ubuntu
I want to create a Python structure similar to the C structure below. Notice that the members are arrays. The reason is because I will be calling a C function which expects arrays of chars in the structure. ``` struct { unsigned char vendorListNumber[5]; unsigned char vendorNumber[5]; } vendrRecord; ``` Looking at this page (https://docs.python.org/2/library/ctypes.html#ctypes.c_char), I don't see a type which is an array or string. Looking at__init__.pyI see this: ``` class c_char(_SimpleCData): _type_ = "c" c_char.__ctype_le__ = c_char.__ctype_be__ = c_char _check_size(c_char) ``` I don't understand this syntax yet ... is there a way I can make my own class which will give me an array of chars?
``` from ctypes import c_ubyte, Structure class VendorRecord(Structure): _fields_ = [("vendorListNumber", c_ubyte * 5), ("vendorNumber", c_ubyte * 5)] ``` Hope it helps!
I am using GDB(peda-gdb) to debug a program, can I write something in a heap address so when the program reach that address It can read it out? I know the address but I do not know how to write something in that address. Thanks.
You can write to the heap using C syntax, with commands that evaluate an expression likeprintorset var. For example, to write an integer value to a specific location: ``` (gdb) set var *(int *)0xYOURADDR = 23 ```