question
stringlengths
25
894
answer
stringlengths
4
863
I want to pass a function a parameter that is a function with two parameters inside, and I can't find how to do it anywhere. I'm trying this code but can't make the func2 use func1 properly. ``` typedef int (*visitFunc) (int n1, int n2); int func1(int num1, int num2) { return num1 + num2; } int func2(int num1, int num2, visitFunc func (int n1, int n2) { return func(num1, num2); } int main() { int x = 2; int y = 5; int z = func2(x, y, func1); printf("%d\n", z); return 0; } ```
TryvisitFunc func. ``` //int func2(int num1, int num2, visitFunc func (int n1, int n2) { int func2(int num1, int num2, visitFunc func) { ``` Also Add#include <stdio.h>.
Many programs assumesizeof(int)==sizeof(unsigned int). IMO it is not and I cant find anything in the Standard which guarantees it. Am I right or wrong?
C11 6.2.5.6 (Types) says "For each of the signed integer types, there is a corresponding (but different) unsigned integer type (designated with the keyword unsigned) that uses the same amount of storage (including sign information) and has the same alignment requirements."
``` package main // // void test(data **void) { // Do something here... // } import "C" import "unsafe" func main() { var data *C.void cData := unsafe.Pointer(&data) C.test(cData) } ``` Above is an example of what I am trying to do but I am receiving a run time error stating cgo argument has Go pointer to Go pointer. How do I resolve this issue? any ideas?
The Go equivalent ofvoid*is anunsafe.Pointer, there's no reason to declare a value of*C.void. The error from your example is not about a Go pointer to a Go pointer (which is a runtime error), you will get an error of(variable of type unsafe.Pointer) as *unsafe.Pointer, which cannot compile. Use the type shown in the error: ``` func main() { var data unsafe.Pointer C.test(&data) } ```
What is the size of data type in an 8-bit microcontroller like int, char, float, double? Also, I wanted to know why 32 bit microcontroller data types have fixed size?
The size of anint,float, etc, is not determined by the microcontroller. The complier choses. Size is influenced by the the native processor width, yet the ultimate decision is a compiler choice with limitations by the standard like anintmust beat least16-bit. "32 bit microcontroller data types have fixed size?" is not a truism. The size of anintis readily found with ``` #include <limits.h> #include <stdio.h> printf("int bit-size: %zu\n", sizeof(int) * CHAR_BIT); // or indirectly with printf("int min/max values: %d/%d\n", INT_MIN, INT_MAX); ```
I'm new to C. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> void demo() { char* s = malloc(10); strcpy(s, "foo"); free(s); } int main() { demo(); } ``` Will this program leak memory with several bytes?
Will this program leak memory with several bytes? No. free(s)will de-allocate all the memory that was dynamically allocated bychar* s = malloc(10);in this example. As @Alexander commented: "Is your concern about the last 6 characters ofs? (past the end of"foo") Worry not,free()will free the whole allocation ofs, regardless of how you used it or what you put in it" Good read:What is a memory leak?
I've been reading a book detailing the C/C++ build process, and it mentions that there's a GNU extension that allows you to specify a function to be run before main() is started. What would be some good use cases for such a function? What's the difference with just doing it first thing when main() starts? I am more after theoretical answers rather than any specific code.
It's useful for libraries to initialize their global state. Without it, the application has to call the libraries' initialization functions frommain(). Examples in the standard C runtime are the initialization ofstdin,stdout, andstderr. While these are initialized by the C runtime itself, the feature you're referencing allows user-written libraries to do similar initialization. C++ probably uses this for calling constructors of global variables.
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.Closed5 months ago.Improve this question I am trying to get theNSHomeDirectory()in pure C ``` #include <CoreFoundation/CFBundle.h> #include <CoreFoundation/CoreFoundation.h> void testFunc() { printf(NSHomeDirectory()); } ```
You need to send theUTF8Stringmessage to theNSStringobject returned byNSHomeDirectory()to obtain a C string. To do this in pure C (Tested): ``` #include <objc/runtime.h> #include <objc/message.h> void *NSHomeDirectory(); void testFunc() { puts(((const char *(*)(void *, SEL))objc_msgSend)(NSHomeDirectory(), sel_getUid("UTF8String"))); // Also use puts() instead of printf() here } ``` Note:Compile using-framework Cocoa
I have a pointer returned bymmapwithMAP_SHARED. Is there a way to query the kernel for how many processes are currently mapping the pointed page? Preferably in a portable POSIX way, but also interested in Linux and macOS.
I have a pointer returned by mmap with MAP_SHARED. Is there a way to query the kernel for how many processes are currently mapping the pointed page? None that I'm aware of. This is part of the kernel internals and changes so quickly normally that makes impossible to have an efficient interface that allows you to query it reliably, not beeing for debugging purposes. Worse, if you want it to be POSIX portable. You need to read the POSIX document for that. Look for it atThe Open Group
I am interested if there is a theoretical speed difference between ``` fwrite(str , 1 , 100 , fp ); ``` and ``` fwrite(str , 100 , 1 , fp ); ``` based on how the function is written in glibc, and how many write calls it makes and how it is buffered (disregarding hardware differences on gcc).
There's no difference formuslorglibc, or theFreeBSD libcsince they all call an underlying function withsize*nmemb: musl ``` size_t fwrite(const void *restrict src, size_t size, size_t nmemb, FILE *restrict f) { size_t k, l = size*nmemb; // ... k = __fwritex(src, l, f); ``` glibc ``` size_t _IO_fwrite (const void *buf, size_t size, size_t count, FILE *fp) { size_t request = size * count; // ... written = _IO_sputn (fp, (const char *) buf, request); ``` freebsd ``` n = count * size; // ... uio.uio_resid = iov.iov_len = n; // ... if (__sfvwrite(fp, &uio) != 0) ```
my fragment shader ``` #version 330 layout(std430, binding = 0) buffer TVertex { mediump vec4 vertex[]; }; ``` results in ``` error: unrecognized layout identifier `binding' ``` I'm using SDL on ubuntu with ``` SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 ); SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 3 ); ``` which gives me ``` Mesa DRI Intel(R) HD Graphics 4400 (HSW GT2) 4.5 (Core Profile) Mesa 21.2.6 ``` what am I doing wrong?
Setting the binding point inside the shader is only supported starting with version 4.2, your shader is specified to use verrsin 3.3. Seethe docsEither you change your version to#version 420. Or you set the binding point inside your application with ``` GLuint bindingPoint = 0; glBindBufferBase(GL_SHADER_STORAGE_BUFFER, bindingPoint, bufferObject); ```
When the input string is e.g. "4.5" I want sscanf to not parse it as a integer. But now it does. My code looks like this:if (sscanf(str, "%d", &val) == 0) { return NULL; }This does not work of course since sscanf parses "4.5" as 4 and does not return NULL Thanks for help
sscanf("4.5", "%d", &val)does not parse "4.5" as 4. It parses the "4" as 4 and leaves the ".5" unparsed. You instead could verify thatsscanfdoes not parse any additional characters from the string: ``` int val; char c; if (sscanf(str, "%d%c", &val, &c) != 1) { return NULL; } ```
I am porting some net-snmp agent code to a system. In that process, I am having to learn about all the predefined objects. My question is: Does SNMP null terminate its admin strings? I have gone through some RFC’s and have read various MIB’s but I just cannot find the information on Null-termination anywhere. The particular admin string is being used as a name/index for an object. Any help would be appreciated
No, every object encoding includes a length, so theNULterminator is not used.
I came across this code in the wild and got very confused. ``` #ifdef __STDC__ double cos(double x) #else double cos(x) double x; #endif { // ... } ``` I fail to see why the latter in the#elsewould be preferable in any circumstances. Are there any reasons to write function definitions as above as opposed to the very standard and widely accepted way as shown below? ``` double cos(double x) { // ... } ```
It may be necessary to use the latter form when compiling code with an ancient compiler or when compiling with a modern compiler but it is necessary to use an ancient version of the C language because some of the code being compiled uses old C features that are incompatible with modern C. Either of these is exceptionally rare these days.
This code produces the (incorrect) result of255 ``` #include <stdio.h> int main() { unsigned char x = 0; x = (x-1)%16; printf("%d", x); return 0; } ``` While this code produces the result15which I feel is correct ``` #include <stdio.h> int main() { unsigned char x = 0; x--; x %= 16; printf("%d", x); return 0; } ``` I was trying to use an underflow to my advantage when this unexpected result happened. Problem does not occur withunsigned intor any other unsigned integer type.
Seethispost. x-1 is implicitly promoted to signed int, effectively becoming-1.-1 % 16(so "remainder of -1 / 16") is still -1, then it is converted back to unsigned char, which is 255.
I want to draw a pattern like this: ``` 567898765 4567654 34543 232 1 ``` But I can't seem to figure it out, because this is the output I'm currently getting: ``` 567898765 45678987654 3456789876543 234567898765432 12345678987654321 ``` This is my code: ``` #include <stdio.h> int main() { int a, b, c, s; for (a = 5; a >= 1; a--) { for (s = a; s <= 4; s++) { printf(" "); } for (b = a; b <= 9; b++) { printf("%d", b); } for (c = 8; c >= a; c--) { printf("%d", c); } printf("\n"); } return 0; } ```
You got it mostly right, only the constant values9and8in thebandcloops are inappropriate, since the triangle's central axis isn't always9; the values are2*a-1and2*a-2, respectively.
This is my code. It is supposed to first of all scan 2 number m and n. Then scan an array of numbers that is x[n]. Number of scanned numbers in second line should be n. But it doesn't work correctly. ``` #include <stdio.h> int main() { int m = 0; int n = 0; int x[n]; scanf("%d", &m); scanf("%d", &n); for(int i = 0 ;i < n;i++) { scanf("%d", &x[i]); } } ``` It just scans 1 number and breaks out of the loop. We should have (i)s from 0 until n-1;
``` int n = 0; int x[n]; ``` This attempts to declare a Variable Length Array of size zero, which already is undefined behaviour. And even if that (having a VLA with room for zero elements) were somehow possible, ``` scanf("%d", &x[i]); ``` ...would also be undefined behavior.
I downloaded the latest versioncurl-8.0.1.zipand unzipped it. I then ran the commandmingw32-make mingw32in the root directory of thelibcurllibrary to build and compile the library. I went over to Code::Blocks, then inSettings -> Compiler... -> Linker Settings, I added the file../lib/libcurl.dll.a. And then inSearch directoriesadded the directory../includetoCompilerandResource compiler, and added../libtoLinker. This is what I got: What am I doing wrong here? Any help would be greatly appreciated.
I fixed the problem. All I needed to do was add the directory oflibcurl.dllto the systemPATHand restart Code::Blocks.
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed5 months ago.Improve this question Ubuntu 22.04.2 LTS - Visual Studio Code 12 how to fix this error
Don't use special shell characters in your file names.&is special, soC&Cppwill bite you, again and again and again and again AND AGAIN AND AGAIN. Special shell characters in filenames arenotillegal, and youcanuse them if you really want to, but... The alternative is to fixallof your shell scripts and config files and whatnot such that all user-provided strings such as file names and parameters and everything else are properly escaped. This is hard. Not using&is easy. Your choice.
I am using GNU11. Consider this: ``` void InitFunc(void) { // // } int OneFunc(int Action) { if (Action == OPT_INIT) { InitFunc(); return 1; } } int OneFunc1(int Action) { if (Action == OPT_INIT) return InitFunc(); // void value not ignored as it ought to be } ``` I know precisely that for OPT_INIT case, I don't need the return at all, using OneFunc1() like a void return. Is it possible to cast before result (or other option) to get rid of that warning? ``` 'void value not ignored as it ought to be' ``` Thanks!
Why not: ``` int OneFunc1(int Action) { if (Action == OPT_INIT) { InitFunc(); return -1; } return 0; // you need return for all cases } ``` You want to economize 1-2 lines? Or this: ``` int OneFunc1(int Action) { if (Action == OPT_INIT) InitFunc(); return 0; } ```
i'm new to microcontrollers, i want to send numbers as numbers through UART using STM32 NUCLEOL053. my script is: ``` uint8_t nums[8] = {0,1,2,3,4,5,6,7}; HAL_UART_Transmit(&huart2, nums, sizeof(nums), HAL_MAX_DELAY); ``` it does not work, how can i solve this? compiler tells me no error or warnings, i already know how to send numbers as string using sprintf but i need to send numbers as numbers
Try converting number in to ASCII and the call the function to transmit on UART. ``` uint8_t nums[8] = {0,1,2,3,4,5,6,7}; char ascii_nums[8][5]; for(int i = 0; i < 8; i++) { itoa(nums[i], ascii_nums[i], 10); // convert the number to a string } ``` Note: You need to useforloop to transmit the numbers one after the other.
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.Closed5 months ago.Improve this question I am building an app using GTK in C, and besides the graphical interface I want to have a topbar widget similar to the discord widget below. Could you provide some information on how to build that?
You could build your widget using the Gnome Shell Extensions GJS Api and then talk to your main (c) application using dbus.
I was trying to make a code that inputs natural number n and outputs first prime number greater than n. I used 2 functionsisPrimeandnextPrime.Question is, why is output always just n+1? ``` #include <stdio.h> int isPrime(int n) { if(n<2)return 0; for(int i=2; i<n; ++i) if(!n%i)return 0; return 1; } int nextPrime(int n) { for(int i=n+1; ; ++i) if(isPrime(i))return i; } int main(void){ int n; scanf("%d", &n); printf("%d", nextPrime(n)); return 0; } ```
The problem is here!n%iwhich is(!n)%iand it is always zero (for n != 0) as!has a bigger priority than% You want: ``` if(!(n%i))return 0; ``` https://godbolt.org/z/Pcxc4746c
I'd like toqsortthe first 100 elements in an integer array and leave the remaining elements untouched. I'm currently trying to do this with the following call: ``` int cmpfunc(const void *a, const void *b) { int xi = *(const int *) a; int yi = *(const int *) b; return (xi - yi); } int my_array[100+some_size]; memset(my_array, 0, sizeof(my_array)); qsort(my_array, 100, sizeof(int), cmpfunc); ``` However, I'm getting a segmentation fault. Is sorting the firstxvalues of an array in C possible?
From the point of view of theqsortfunction it makes no difference if there are any more array elements after the first 100, since it only gets a pointer to the start of the array, and the number of elements after the starting pointer. So, yes, assuming it's possible to sort an array with 100 elements, it's also possible to sort the first 100 elements of a larger array.
This question already has an answer here:Why can I not modify a string literal in c?(1 answer)Closed5 months ago. The following program is throwing segmentation fault. ``` #include<stdio.h> int main(){ char *p = "exs"; char x; x = (*p)++; printf("%c\n",x); return(0); } ``` Please help. I was expecting 'f' but got seg fault.
You need to copy the string into writeable memory first usingstrdup. Then use++(*p)instead of(*p)++to get the value after incrementing the first byte. Although not necessary in short-lived processes, it is a good style tofree()the memory allocated withstrcpy()when it is not used to avoid memory leaks. With these changes applied, the program would look like this: ``` #include<stdio.h> #include<string.h> #include<stdlib.h> int main(){ char *p = strdup("exs"); char x; x = ++(*p); printf("%c\n",x); free(p); return(0); } ```
I am trying to set the mod of a new file to match the old one. My Qt5/C++ codes is roughly: ``` stat(oldFileName.toLatin1().data(), &sb); bool success = chmod(newFileName.toLatin1().data(),sb.st_mode) ``` The sb.st_mode value at the time of chmod being called is 33261 (octal 100755). The chmod() call fails and sets errno to 13 (permission denied). yet the program is running as uid 0 gid 0. UPDATE: Looks like stat() also includes file TYPE information in the higher bits I need to remove. I tried to use (sb.st_mode & 0x1FF which yields 0755) as the value for chmod but still fails.
Interestingly chmod() and chown() return 0 for success, -1 for failure. Which is the opposite of C/C++ standard (0 for false, non-0 for true). So you have to reverse the function return value to use as a boolean.
I did some experiments, but could not find a way to do that : Is there a way to tell the system to "finish a file" early ? Like, writing some weird old looking char that will, somehow, be interpreted as "Well, this is the end of this file." by the Linux kernel. The goal would be some interesting ways to "stop" a file, by cutting it in some place (might be hard to do due to the file system handling, knowing exactly the size, but uh, why not try ?) PS: The final goal would eventually be to implement that in c (write a program that write this weird byte on a file and the file size and content is updated like magic)
On Linux, there is no special character that will be interpreted as the end of the file. However, you can use the Linux system callstruncateorftruncateto truncate a file to a specific length.
I have trouble understanding the difference between bitwise concatenate and or. For example, I have to bianry values which is 1111 and 0000. If I do 1111 | 0000, will I get 1111 or 11110000? And if I get 11110000 as the result, when should I use | as or operation?
1111 | 0000is1111. There is no bitwise concatenate operator. You can use left shift<<to move bits to the left1111 << 4is11110000.
I'm trying to free a bunch of things with different types, and so I think I might be able to free all of them using one function by adding them to a pile ofvoid *cells. My question is: is it safe to save anSDL_Surface*asvoid *and use thefree()function without the need ofSDL_FreeSurface()?
No, you have to useSDL_FreeSurface. (Evidence:what it does) Except in specific cases, it's never safe to just use one free function instead of another. Youfreethings you allocate withmalloc. YouCloseHandlethings opened withCreateFile(on Windows). Youfclosefiles you opened withfopen. And so on.
I am using lcov/gcov to measure test coverages in a project. However, the test coverage report includes some lines signaled as unhitted that shouldn't be there. For example: Comment lines, function definitions splitted across two lines, opening brackets, etc are counted towards total coverage as not covered. How can I instruct lcov/gcov to ignore such lines?
Finally, I solved the issue. Looking at gcov man page (https://linux.die.net/man/1/gcov) I found thatgcov works only on code compiled with GCC . It is not compatible with any other profiling or test coverage mechanism. Default C compiler in my system was ClangC. Settinggccas compiler when callingcmakethis way $ cmake . -DCMAKE_BUILD_TYPE=Debug -DCMAKE_C_COMPILER=/usr/bin/gcc solved the problem.
new to emudev starting out by building a CHIP8 emulator in C. why is its4k memorytakes aschardatatype? I believe I am missing some really fundamental information. help also, what are flags? CHIP8 has 16 (15?) registers VN from 0-F to carry flags. What does it mean? Thanks :)
The emulator usechar *datatype because in most systems the char size is 1 (1 byte) so is the ideal type to identify generic bytes in memory. As said by othersunsigned charoruint8_t(form stdint.h) would be preferable for this usage. You can think about flags as a set of booleans that get set, unset automatically. The most simple one is the Overflow flag that is set if the result of the previous operation add an overflow.
Here is my code: ``` #include <stdio.h> int main() { char op; int num1, num2; printf("Enter the operation(+,-,/,*,!,^) : "); scanf(" %c", &op); switch (op) { case '+': printf("Enter the first operand : "); scanf(" %d", num1); printf("Enter the second operand : "); scanf(" %d", num2); printf("%d", num1 + num2); break; } } ``` when I run this. code stops after me entering first operand. I added space beforescanfbut it didn't solve the problem below.
You forgot to add the address operator (&) in front of thenum1andnum2variables in the calls toscanf. Modify those two lines like this: ``` scanf(" %d", &num1); scanf(" %d", &num2); // ^add the & ```
``` int num = 0, k = 0; scanf("%d %d", &num, &k); int* A = &num; for (int i = 0; i < num; i++) { scanf("%d", &A[i]); //scanf("%d", A+i); } ``` in that code, I want 4 5 1 3 2 integers put in the array A input is ``` 5 7 4 5 1 3 2 ``` but in debug mode, there are ``` *A 4 int *(A+1) 5 int *(A+2) 1 int *(A+3) 3 int *(A+4) -858993460 int *(A+5) -858993460 int ``` why is the*(A+4)not 2?????? I tried the num+1, but that is not the ultimate solution. ``` for (int i = 0; i < num+1; i++) { scanf("%d", &A[i]); } ```
To define an array, you'd do ``` int A[num]; ``` Your variableAis a pointer to an integer, not an array. You can treat it as an array, as arrays are basically pointers in C. But the memory you're writing fromscanf()is not 'allocated'.
All descriptions of getline() and getdelim() say that they return the number of characters read, or -1 at end of file or error. Can they read no characters while not at end of file? Can I assume the return value will be nonzero?
No,getline()andgetdelim()cannot return 0. Normally,getline()will read characters including the trailing'\n'that marks the end of a line, so it will always read at least one character. The only exception to this is that the last line of input might not have a trailing'\n'character. If the last line is not empty,getline()will read the characters making up the line and return a non-zero count. It's not possible for the last line to be emptyandhave no trailing'\n'character. That's just an end-of-file condition, which causesgetline()to return -1. The same applies togetdelim(), with the delimiter character replacing the'\n'character.
I have the following C file ``` int foo (int input) { if (input == 0) input = 1; return input; } ``` When I create an object file usinggcc foo.c -m32 -Wa,-march=i486 -c, everything goes well. However, when I add a-O3to the command, I get the following error: ``` /tmp/cc7br7gY.s: Assembler messages: /tmp/cc7br7gY.s:12: Error: `cmove' is not supported on `i486' ``` Do I have to provide an additional option for the assembly optimizer to tell it that I want instructions that will work on i486? gcc --versionoutputsgcc (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0.
You aren't telling the compiler to compile to the arch, just the assembler (which I'm not really sure you need to do). Pass a plain-m32 -march=i486if that's what you want to do (or useany other archas you require).
``` #include <stdio.h> void fun(int a, float b) { int c; c = a + b; printf("Value ----- c %d", c); } int main() { void (*foo) (int, int) = &fun; (*foo)(3,2); return 0; } ``` I just want to know how this code flow works. the above code prints 3 as output i am not sure how it is working
Your program invokedundefined behaviorby using a pointer having incompatible type to call a function. (pointervoid (*)(int, int)is used to call a functionvoid fun(int a, float b), the type of the 2nd parameter differs) The reason for this paticular resultmay bethat you are using a calling convention where floating-point arguments are passed in different ways (different registers, for example) than integer arguments and there happened to be zero or some small value in such area to pass floating-point values.
This question already has answers here:What are bitwise shift (bit-shift) operators and how do they work?(10 answers)Closed6 months ago. ``` hour = (bufm[1] &= ~((1 << 7) | (1 << 6) | (1 << 5))); ``` I did not understand what this code does and therefore I cannot translate it into dart. I see that there are bitwise shifts
&=means take only the bits that are set to 1 in both operands ~reverses all bits, <<moves the bits to the left n times, |combines bits from operands so ``` hour = (bufm[1] &= ~((1 << 7) | (1 << 6) | (1 << 5))); // 128, 64, 32 hour = (bufm[1] &= ~(128 | 64 | 32)); // ~0x000000E0, reverse bits hour = (bufm[1] &= 0xFFFFFF1F); // keep only those bits, ie. remove bits 5 6 7 ``` I assume hour is an int (32 bits). It removes bit 5, 6 and 7 frombufm[1]and stores it inhour.
I would like to get the thread ID in a numeric form with the following code: ``` #include <string.h> ... pthread_t ptid = pthread_self(); unsigned long long threadId = 0; memcpy(&threadId, &ptid, std::min(sizeof(threadId), sizeof(ptid))); ``` But I get this error: ``` error: ‘std’ undeclared (first use in this function) 17 | memcpy(&threadId, &ptid, std::min(sizeof(threadId), sizeof(ptid))); | ^~~ ``` How can I fix that?
std::minis for C++. Instead of that, you should define a function to obtain the smaller (not larger) value by yourself and use that. ``` size_t min_size(size_t a, size_t b) { if (a <= b) { return a; } else { return b; } } ``` ``` memcpy(&threadId, &ptid, min_size(sizeof(threadId), sizeof(ptid))); ```
Please see the post Given the below data in the file: ``` Jim: 100.00 Amed John: 200.00 ``` ``` if (line[len] != '\0') { printf("extra characters: %s\n", line + len); } ``` the first invalid line will be: ``` Jim: 100.00 Amed ``` and the len 12 and the output will be: ``` extra characters: Amed ``` How doesline + lengive: ``` Amed ```
line + lenwill incrementline's value (a memory address) by the size of its underlying data type. So iflineoriginally was: ``` Jim: 100.00 Amed ``` line + 12would evaluate to: ``` Amed ``` See also:Pointer Arithmeticandc-faq.com section 4
Please see the post Given the below data in the file: ``` Jim: 100.00 Amed John: 200.00 ``` ``` if (line[len] != '\0') { printf("extra characters: %s\n", line + len); } ``` the first invalid line will be: ``` Jim: 100.00 Amed ``` and the len 12 and the output will be: ``` extra characters: Amed ``` How doesline + lengive: ``` Amed ```
line + lenwill incrementline's value (a memory address) by the size of its underlying data type. So iflineoriginally was: ``` Jim: 100.00 Amed ``` line + 12would evaluate to: ``` Amed ``` See also:Pointer Arithmeticandc-faq.com section 4
Consider this code: ``` int main(void) { printf("%s", "the string"); printf("%s", "the string"); } ``` Is there any standard saying that the program memory will be allocated only once for"the string"and not twice (or any other number of times, depending on how many times the literal is used)? When I examine the output elf file of my program, for such a case I can only find the string occurring just once and I am trying to figure out whether this is a rule, or is it compiler dependent.
Modern compilers and more recently link time optimizers automatically share string literals across modules or the whole program. There is no need for any particular indication in the code, but the programmer should not rely on this to always happen as some platforms or debugging modes might alter this behavior, that is indeed compiler dependent.
This question already has an answer here:Variable length arrays and static declaration in c(1 answer)Closed6 months ago. I am trying to create a static array where the length of the array could differ. I am doing this so that i can return the array from a function without using pointers. I have tried: ``` void arrExample1(int size){ #define len size satic int arr[len]; } ``` ``` void arrExample2(int size){ enum { len = size }; static int arr[len]; } ``` Neither of these have worked and I am at a loss of what I should do next. Can I get some advice or pointed in the correct direction?
Unfortunately you can only define it dynamicly. Here is how, in case u need it:Dynamicly creating an array
If not, can it be made asynchronous so other code can be executed without having to wait for the flushing to be completed?
The Standard C functionfflush(stream)causes any unwritten data for that stream to be delivered to the host environment to be written to the file. This occurs synchronously with respect to the current process, ie:fflush()does not return until the data has been delivered to the system, but the system may cache the file system sofflush()does not wait for the data to be written to the file system on disk or through the network. There is no standard function to make this happen asynchronously. You could conceivably use a separate thread to flush the stream buffer asynchronously, but fiddling with the same stream in different threads is not recommended.
I get a "Data argument not used by format string" error when I compile the following code: ``` #include <stdio.h> int main(void) { int kor[3], eng[3]; int i; for(i=0;i<3;i++){ printf("1번째 학생 성적 입력 \n", i+1); // error shows up for this line printf("국어 : "); scanf("%d",&kor[i]); printf("\n영어 : "); scanf("%d",&eng[i]); } printf("=== 학생 성적 출력 ===\n"); printf("학번 국어 영어 \n"); for(i=0;i<3;i++){ printf("%d %d %d \n",i, kor[i], eng[i]); } } ```
``` printf("1번째 학생 성적 입력 \n", i+1); ``` You have provided an argumenti + 1toprintf()but it has no corresponding format specifier, so it goes unused. From the C11 standard: [...] If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored [...]
I need some array of array of const strings. This compiles just fine in C ``` char* names[] = {"John", "Adrian", "Mary", NULL}; char* towns[] = {"Paris", "London", "Amsterdam", "Madrid", NULL}; char** test[] = {names, towns, NULL}; ``` Is there a shorter way to do them all in one, like this? ``` char** test[] = {{"John", "Adrian", "Mary", NULL}, {"Paris", "London", "Amsterdam", "Madrid", NULL}, NULL}; ``` Gives a ``` warning: excess elements in scalar initializer ``` Thank you in advance!
You can usecompound literalof array type from C99. ``` char** test[] = {(char*[]){"John", "Adrian", "Mary", NULL}, (char*[]){"Paris", "London", "Amsterdam", "Madrid", NULL}, NULL}; ```
I am trying to do kind of a parser in C to read a JSON. I need to parse a table like this: ``` char rosa[1024] ="\"358\":{\"myItem\":12,\"1\":{1,0},\"2\":{0, 0}},\"352\":1"; sscanf(rosa, "%[}}]s",rosa); ``` Output:"358":{"myItem":12,"1":{1,0 I need to extract first Key-Value. So, I tried to do asscanfbut it reads until first}, not till}}. Any suggestion? Best regards.
Usestrstr(rosa, "}}")to detect if and whererosa[]contains}}. ``` char *end = strstr(rosa, "}}"); if (end) { printf("<%.*s>\n", (int) (end - rosa) + 2, rosa); } else { printf("Not found\n"); } ```
Hello I have a simple problem in C I think. I was wondering how one would go about including headerfiles in the same parent directory as the source file, but where the source files are in a subdirectory called source and the headers in a subdirectory called "headers". This is my first time posting a question :) I simply tried to include using the "..." but this only seems to work with files in the same directory and doesn't check the subs. My idea was to maybe move my headers to /usr/include but then it would be very annoying to find every time. Thanks!
``` #include "../headers/API.h" ``` definitely used to work for me, and it really should work for you, as well. However, it would sound as if the right thing to do was to tell your build system to include the headers directory in the header search path (-Ion all POSIX-alike targeting compilers)
I was reading a tutorial on operator overloading in C++ when I saw this: In C++, operators are implemented as functions. By using function overloading on the operator functions, you can define your own versions of the operators that work with different data types.The compiler comes with a built-in version of the plus operator (+) for integer operands -- this function adds integers x and y together and returns an integer result. Are operators in C also implemented as functions? If not, how are operators implemented in C? Could it also be that operators being implemented as functions for POD types is something that only certain compilers do?
This statement In C++, operators are implemented as functions Is wrong. Operators for fundamental types are predefined in C and C++. But in C++ you may overload operators as functions for user-defined types. In C there is absent such a possibility.
One of the greatest things about Python is the flexibility ofdynamic arrays (lists). It's so useful I find it hard to believe there isn't a library for this already included in C. Thisquestionindicates that there is no standard library for this. Apparently,glibcincludes functionality for queues, but as I'm on a windows machine this is not helpful. As the question is 10 years old, I'm wondering if there's been an update. Is implementing the functionality yourself still the only way to get something like a Python list or is there a standard C library that allows you to use dynamic arrays?
There is currently no standard library for dynamic arrays, but it's not hard to implement the functionality withrealloc()and family. Here's something you can start with: ``` struct dynamic_array { void *array; size_t occupied_size; size_t allocated_size; }; ``` See:Dynamic arrays in C.
``` struct A { int zero_member[0]; int other; }; struct B { int* zero_member_ptr[0]; int other; }; printf("%d %d", sizeof(struct A), sizeof(struct B)); ``` Output: ``` 4 8 ``` Why the difference? In reality I'm using this with Android NDK, and I've tested it atCompiler Explorerwithout any flag. So, if this is not standard ISO C program, this problem should have no standard answer.
"Why the difference?" Likely due to padding to meet pointer alignment requirements - even if it is size 0.
How can I solve this problem? error: expected an expression ``` for (int i = 0; i < n; i++){ ^ ``` Function that I try to implement: ``` void initRacks(struct rack_t *racks, int n) { for (int i = 0; i < n; i++){ racks[i].widthA = i + 2.5; racks[i].widthB = i + 1.5; } } ```
It depends on which version your compiler is. Declaring theint i;above the for loop will solve the error. More detailed answer:C for loop int initial declaration
``` printf("Date Order time\t\t: ");scanf("%02d-%02d-%04d", &d, &m, &y); printf("\nDate order\t\t: %02d-%02d-%04d", d, m, y); ``` this is what happen if I type1 ``` Date Order : 01-4227112-0000 ``` I want to try this ``` Date Order : 01-00-0000 ```
Variables corresponding to failed conversion won't be changed byscanf(), so you should initialize the variables before callingscanf(). ``` d = m = y = 0; /* add this */ printf("Date Order time\t\t: ");scanf("%02d-%02d-%04d", &d, &m, &y); printf("\nDate order\t\t: %02d-%02d-%04d", d, m, y); ```
Whenever I am usingintfor returning multiple values to the main, I am getting this error. ``` int search(int key, struct node *temp) { if(temp == NULL) return 0; else if(temp -> data == key) return 1; else if(key < temp -> data) search(key,temp -> left); else search(key,temp -> right); } ```
Return something from all paths. Simple callingsearch()does not cause its return value to be returned from withinsearch(). ``` int search(int key, const struct node *temp) { if (temp == NULL) return 0; if (temp->data == key) return 1; if (key < temp->data) return search(key, temp->left); // return added. return search(key, temp->right); // return added. } ``` Also: Unneededelses removed.Useconst struct node *tempastempreferenced data is never changed.Other simplifications exist.
I recently foundedCHAR_BITand I tried to change it to 9 (or anything above 8) ``` #include <limits.h> #define CHAR_BIT 9 ``` Indeed when Iprint CHAR_BIT, it returns 9(that's correct). But when I want to use a char, thinking it will have a higher range, it does not.Somehow it is still with 8 bits. Am I doing something wrong? Or it's just not possible to change the number of bits of a char? (I don't think so, but idk) ``` #include <stdio.h> #include <limits.h> #define CHAR_BIT 9 int main() { unsigned char B = 260; printf("%d\n",B); //returns 4 (260-4->254, 8 bit char) } ```
The number of bits in a byte is a property of the underlying hardware, and therefore cannot be changed. TheCHAR_BITmacro just gives you a way to programmatically know what that value is.
I would like to write a C program to test if PipeWire is running. If it's not I will fallback to using ALSA. What's a good way to accomplish this?
test if PipeWire is running in C is to use the PipeWire API to check the availability of its core object. ``` gcc -o test test.c -lpipewire-0.3 ``` ``` #include <pipewire/pipewire.h> int main() { pw_init(NULL, NULL); // initialize the PipeWire library struct pw_core *core = pw_context_connect(pw_context_new(NULL, NULL), NULL, 0); // connect to the PipeWire core if (core != NULL) { // check if the connection was successful pw_core_disconnect(core); // disconnect from the PipeWire core return 0; // PipeWire is running, exit with success code } else { return 1; // PipeWire is not running, exit with error code } } ```
For example, consider this snippet: ``` # ifndef OPENSSL_NO_DEPRECATED_3_0 OSSL_DEPRECATEDIN_3_0 size_t HMAC_size(const HMAC_CTX *e); OSSL_DEPRECATEDIN_3_0 HMAC_CTX *HMAC_CTX_new(void); OSSL_DEPRECATEDIN_3_0 int HMAC_CTX_reset(HMAC_CTX *ctx); OSSL_DEPRECATEDIN_3_0 void HMAC_CTX_free(HMAC_CTX *ctx); # endif ``` I want to understand what exactly OPENSSL_NO_DEPRECATED_3_0 means, the wordplay is confusing to me, is it not deprecated or is it deprecated?
From the OpenSSL page: OPENSSL_NO_DEPRECATED— If this macro is defined, all deprecated public symbols in all OpenSSL versions up to and including the version given byOPENSSL_API_COMPAT(or the default value given above, whenOPENSSL_API_COMPATisn't defined) will be hidden.
I want to be able to debug C and Rust Code in the Helix Editor. According to its documentation, I need the lldb of VSCode, codelldb. Any other DAP that works is fine for me. I am using a MacBook Pro 2022 with the M2 Processor (arm64) vscode-lldb GitHub Repository CodeLLDB VSCode Extension Couldn't find it on homebrew or macports. I tried to build the v1.8.1 tag from source but got compile errors. I think I am doing something fundamentally wrong.
github releasejust extract the file as zip and find the executable binary in there: /extension/adapter/* place is somewhere in the path so helix could find it
Network always goes down after setting interface to promiscuous mode via: ``` memset(&ifr, 0, sizeof(ifr)); strcpy(ifr.ifr_name, if_name); ifr.ifr_flags |= IFF_PROMISC; ioctl(sock, SIOCSIFFLAGS, &ifr); ``` Is it possible that the router knows about this attempt and it blocks my connection? If so, how is it that applications like Wireshark stay on? Is there a way to hide this mode?
Your code doesn't just set the IFF_PROMISC flag - it also clears all other flags, such as IFF_UP which makes the interface up. Therefore, your code makes the interface go down. If you only want to change one flag, you can useSIOCGIFFLAGS(G for Get) to get the old flags, then edit the one flag you want and set them.
I think the value ofzshould be 40 becausea[5]has 20 elements, and the space between it anda[3]also has 20 elements. However, the actual value ofzis 2. Can anyone explain this concept? ``` #include <stdio.h> int main() { int a[10][20]; int z = &a[5] - &a[3]; printf("%d\n", &a[3]); // the address information is 6421740 printf("%d\n", &a[5]); // the address information is 6421900 printf("%d\n", z); // z value is 2. why? } ```
Pointer arithmetic is done in the units of the pointed-to type. In this casea[5]anda[3]are both elements of an array of typeint [20], and&a[5]and&a[3]both have typeint(*)[20]. They are 2 array element apart, so the difference between them is 2. It doesn't matter that the underlying type is also an array.
For example: ``` printf("%d", -1 & 3); ``` The output is 3. I tried with other number and it's the same. sorry for short question, but I don't think I should make it long for no reason. I searched around and did not find answer to it.
Some1)(not all) of the bitwise operators don't care about signedness of the operands but instead look at the raw binary representation of the variable. In case of the negative value -1, the raw binary in the common two's complement format looks as1111....1111(all ones). As an example, lets assume 16 bitint, 2's complement: ``` Dec Bin -1 1111 1111 1111 1111 3 0000 0000 0000 0011 ------------------------- & 0000 0000 0000 0011 = 3 dec ``` 1)Specifically,& | ^ ~and their compound assignment equivalents only look at the raw binary representation.
ARM GCC 12 version - how to ensure thatmallocandfreefunctions don't get linked by the linker and throw abuilderror if called? Looking for similar todeletein C++, that is used to make sure function is not included (like hidden copy/move constructors, for instance).
functions don't get linked by the linker and throw a compilation error if called? Contraverting requirements. If the compiler throws anerrorthen nothing will be linked as it will stop the build process. Add to the linker script: ``` PROVIDE(malloc = 0); ASSERT(!malloc, "MALLOC PRESENT - ALERT!!!"); ``` same for other symbols you want to be warned about (actually linking will terminate)
I have triedputs("”");,puts("\”");but every time I getöas output so escape character doesn't works. Do I have wrong code page? If it is possible I don't want to useprintf("%c",smth);
The correct expression is the 2nd one with a regular double quote: ``` puts("\""); ``` If you want to use the UTF-8 character then it's a terminal font / encoding issue and not a C question: ``` $ echo '"”"' | od -c 0000000 " 342 200 235 " \n 0000006 ```
I am new to Windows APIs. I am doing an exercise on printing the computer name to the console. Here is the code I have so far: ``` wchar_t compName[MAX_COMPUTERNAME_LENGTH+1]; DWORD maxSize = MAX_COMPUTERNAME_LENGTH+1 ; BOOL getName = GetComputerNameW(compName, &maxSize); wprintf(L"Computer name is: %s",compName); ``` The issue is on the output. I only seeComputer name is Don the console, when I should seeDESKTOP-XXXXXX. What am I doing wrong? I believe I am calling the right functions, per the MSDN docs. I have seen posts on StackOverflow regarding this issue, but it is in C++ and not C. I feel like it has something to do with me printing a Unicode string.
The format specifier%sis for printing a string pointed at bychar*, even inwprintf. You should use format specifier%lsto print a string of wide characters. printf, _printf_l, wprintf, _wprintf_l | Microsoft Learn
``` #include <stdio.h> #define A "hello world\n" void main() { printf(A); } ``` ``` $ gcc -gdwarf-4 -g3 a.c \ && gdb -ex 'set confirm off' \ -ex 'break main' \ -ex 'run' \ -ex 'p A' \ -ex q \ a.out ... Breakpoint 1, main () at a.c:5 5 printf(A); $1 = "hello world\n" $ gcc -gdwarf-5 -g3 a.c \ && gdb -ex 'set confirm off' \ -ex 'break main' \ -ex 'run' \ -ex 'p A' \ -ex q \ a.out ... Breakpoint 1, main () at a.c:5 5 printf(A); No symbol "A" in current context. $ gcc --version gcc (GCC) 12.2.1 20230201 ... $ gdb --version GNU gdb (GDB) 12.1 ... ```
As ssbssasuggestedthis looks like abugingdb-12.1. The fix is released ingdb-13.1
1. Lexical Pitfalls:For another example, consider this statement: ``` if (x < big) big = x; ``` Each non-blank character in this statement is a separate token, except for the if keyword and the two instances of the identifier big.In fact, C programs are broken into tokens twice.... — FromC Traps and Pitfalls, Andrew Koenig. My question is: Why is theifkeyword and the two instances of the identifierbignot separate tokens? What are they?
The text means to say "every character in this expression is a token, except the characters used to formifandbig". In case ofifthenifis a token, but not the charactersiandfrespectively. That is, this expression consists of the tokensif,(,x,<,big,),big,=,x,;.
While reading or writing to file in binary mode, what's the difference between putting '+' between 'r'/'w' and 'b' or putting it right after them both? I searched and i foud that this affects the behavoir of reading/writing to the file but i don't understand what that means...
From the C Standard (7.21.5.3 The fopen function) r+borrb+open binary file for update (reading and writing) So there is no difference in specifying the mode. Here are some other equivalent mode specifications w+borwb+truncate to zero length or create binary file for updatew+bxorwb+xcreate binary file for updatea+borab+append; open or create binary file for update, writing at end-of-file
Now to compare 2Tcl_Objs, I extract the 2 strings and compare with each other like this : ``` const char* str1 = Tcl_GetString(myObj1); const char* str2 = Tcl_GetString(myObj2); if (!strcmp(str1 , str2)) { // do something } ``` Instead of doing this, is there a way to compare the two objects directly with Tcl API?
As far as I can see,the internalTclStringCmpfunctionbasically does the same thing: callsTcl_GetUnicodeFromObjorTcl_GetStringFromObjon the objects andmemcmps them.
Now to compare 2Tcl_Objs, I extract the 2 strings and compare with each other like this : ``` const char* str1 = Tcl_GetString(myObj1); const char* str2 = Tcl_GetString(myObj2); if (!strcmp(str1 , str2)) { // do something } ``` Instead of doing this, is there a way to compare the two objects directly with Tcl API?
As far as I can see,the internalTclStringCmpfunctionbasically does the same thing: callsTcl_GetUnicodeFromObjorTcl_GetStringFromObjon the objects andmemcmps them.
I am learning pointers in C. I understandint * p = &awill assign the address ofa. Instead of this way I chose to store the address in another variable and then assigned it to the pointer variablep. I was expecting that program will execute as it usually works with the above mentioned statement however my code is crashing at the line*p=20;. I am not any getting idea what is going on here .Please help me to understand it. ``` #include<stdio.h> void main(){ int a=10; int adr = &a; int *p=adr; *p=20; printf("%d",a); } ```
Here is an annotated version of your program. Running it should help illustrate what's going on. ``` #include <stdio.h> int main() { int a = 10; printf("&a = %p\n", &a); int adr = &a; printf("adr = %x\n", adr); int *p = adr; printf("p = %p\n", p); *p = 20; printf("%d", a); } ```
I would like to be able to build project releases from a batch file rather than the GUI as in my opinion it makes the whole process more controlled. I'm struggling to find examples of this online. Has anyone else done it?
Im on Linux but it should be similar on Windows. I went to my project right, clicked the project name inProject Explorer, hovered overShow In, and clickedSystem Explorer. I then entered the directoryReleasewhich there should be aMakefileon Linux, in the release directory, I runmake. ~/STM32CubeIDE/workspace_1.7.0/TEST/Release$ make This will generate a.binfile and an.elffile, which can be used to program the chip withSTM32CubeProgramer.
Okay, so this is the function I'm usingremove(): ``` int fmove(const char * filepth, const char * destpth) { FILE * fp; fp = fopen(filepth, "r+"); FILE * fpdest; fpdest = fopen(destpth, "w"); if ((fp != NULL) && (fpdest != NULL)) { char fpdata[999]; fgets(fpdata, 999, fp); fputs(fpdata, fpdest); remove(filepth); } else { prtmessage("ERROR", "Cannot move file!"); return 1; } return 0; } ``` but theremove()returns -1. I know that arrays return their pointers (am I telling it right?), but is there a way to pass the string in thefilepathtoremove()?
From the C Standard If the file is open, the behavior of the remove function is implementation-defined. You need to close the file before callingremove().
I need to confirm my code if I'm using ANSI C (C89/C90) and I notice this: Even if I have selected ASNI C (C89/C90) standard in Eclipse CDT. Question: It is told that ANSI C does not use__STDC_VERSION__but why do I see the same value for__STDC_VERSION__as199901Lfor C99 standard in Eclipse CDT? I'm using GCC compiler for Lubuntu Linux.
I have tested it. Eclipse CDT simply shows the oldest value programmed. It does not have anything in common with the actual__STDC_VALUE__seen by the compiler. When you compile as C90__STDC_VALUE__is not defined and value shown in the Eclipse is not valid. I believe that it is an Eclipse bug. Colouring is also wrong.
I have a problem that need to resample 16 bits depth to 32 bit depth mp3 in c program. any suggestion where I can find some repo as reference or web site to start with?
Decode the MP3 into WAV or AIFF format with PCM coding, up-sample, then re-encode.FFMPEGis good for that. However word of advice: You don't gain audio quality doing this, You only have 16 bits of information per sample, you can't add more to it. That's how information theory work.
Bind expects a pointer tostruct sockaddr(https://man7.org/linux/man-pages/man2/bind.2.html). Is it safe to free this structure immediately after the call tobindor is it safe to free this only when the socket is closed? If it is safe to free the structure immediately after the call tobind, does the kernel keep a copy of the address?
You can free it immediately after the call. Usually thesockaddrorsockaddr_inis declared on the stack. But if you're passing addresses around by pointer, you're ok free it immediately afterbindreturns. Same holds true for other socket functions likeconnectandsendto.
According to the man page for getopt and getopt_long, the GNU version reorders argv so that anything resembling a flag will be first, then it will return -1 when it reaches the first string that is not a flag. It also says that when optstring[0] is set to '+', it will not reorder the arguments. How do I set optstring[0] to '+'? I tried simply tossing in a optstring[0] = '+'; assignment statement, and I rightfully got that optstring is undeclared.
optstringis the third argument togetopt_long, declared as: ``` int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex); ``` Call the function with anoptstringthat begins with+: ``` getopt_long(argc, argv, "+abc:d:f:", long_options, &option_index); ```
I have a struct in C: ``` struct A { int a; int b; int c; } ``` When initializing the struct clang-format reformats the code as follows: ``` struct A name = {.a = 1, .b = 2, .c = 3}; ``` How can I tell clang-format to put any member in its own line? Like so: ``` struct A name = { .a = 1, .b = 2, .c = 3 }; ```
Adding a trailing comma should fix this problem. ``` struct A name = { .a = 1, .b = 2, .c = 3, // <-- this trailing comma is needed }; ```
I am learning how to use terminal escape codes on Windows. I know how to move cursor position and how to do a few other things. But how do I receive input? For instance, if I want to navigate around with the arrow keys, how would I do that?
Keyboard input is usually platform specific. ncurses can be used on Linux and macOS while there exists an alternative library for Windows called pdcurses. Another option is <conio.h> which is offered by most C compilers that target Windows including mingw. <conio.h> lets you use _getch() and _getwch() which are functions that get a character from the console. A link to them:https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/getch-getwch?view=msvc-170 Here is a SO question that uses _getch() to detect when the arrow keys are pressed:how to detect the ESC key in C? Edit, this might help as well:https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
I'm trying to manually import symbols fromlibncurses.so. This works fine for function pointers and normal variables likestdscrorCOLORS. However,ncurses.halso defines a global array namedacs_map: ``` extern NCURSES_EXPORT_VAR(chtype) acs_map[]; ``` How can I import this usingdlsym()? My problem here is thatacs_mapis an array, not a pointer so I'm not sure if it's allowed to do something like this: ``` chtype **ptr = dlsym(lib, "acs_map"); chtype *acs_map = *ptr; ``` But I think I have to use a pointer somehow because I can't assign a new value to an array variable, can I? So what's the recommended way to importacs_mapusingdlsym()?
Since arrays decay to a pointer to their first member, you can use a pointer type to refer to the array object. ``` chtype *ptr = dlsym(lib, "acs_map"); ```
I'm trying to manually import symbols fromlibncurses.so. This works fine for function pointers and normal variables likestdscrorCOLORS. However,ncurses.halso defines a global array namedacs_map: ``` extern NCURSES_EXPORT_VAR(chtype) acs_map[]; ``` How can I import this usingdlsym()? My problem here is thatacs_mapis an array, not a pointer so I'm not sure if it's allowed to do something like this: ``` chtype **ptr = dlsym(lib, "acs_map"); chtype *acs_map = *ptr; ``` But I think I have to use a pointer somehow because I can't assign a new value to an array variable, can I? So what's the recommended way to importacs_mapusingdlsym()?
Since arrays decay to a pointer to their first member, you can use a pointer type to refer to the array object. ``` chtype *ptr = dlsym(lib, "acs_map"); ```
``` #include <stdio.h> int main() { int num = 90; for (int x = 0; x <= num; x++) { printf("%d", num % x); } return 0; } ``` My code doesn't seem to do anything. I wanted my code to print the remainders if we divide 0 to 90 to 90 but my code doesn't seem to do anything, please help. :(
Your program does not print anything because it crashes at the first iteration of the loop when computingnum % xforx = 0. This is a division by0, which has undefined behavior and stops the program on most current systems. Start the loop at1to avoid this case. Also output a newline after each value to make the output readable: ``` #include <stdio.h> int main(void) { int num = 90; for (int x = 1; x <= num; x++) { printf("%d\n", num % x); } return 0; } ```
Suppose we have 2 ints 5 and C(hexidecimal representation of 12) and we want to get a char, which is the concatenation of 4 bits of the first number and 4 bits of the second number. As a result in my example, i have to get a char with bits: 0101 1100. Can somebody help me? Thank you! This issue arose from the following scenario: in my program I work directly with bits. To work with bits I use the char data type. Initially, I need to work with 4-bit numbers, but the char size is 8 bits. I have 16 int numbers, which are 4-bit numbers (0, 1, ..., 15), I need to write them using a char, and for this I need to put two ints in one char.
Caveat: OP states values of 'first' and 'second' are between 0 to 15 inclusive. ``` unsigned char hi = 0x5, lo = 0xC, result; result = (hi << 4) | lo; // low 4 bits of 'first' OR'd with low 4 bits of 'second' ``` That should do it..
``` int firstOcc(int a[],int m,int x) { int high=m-1,low=0,mid,index=-1; while(low<=high){ mid=(low+high)/2; if(a[mid]<x){ mid=low+1;} if(a[mid]>x){ mid=high-1;} if(a[mid]==x){ index=mid; high=mid-1;} } return index; } ``` why is my function isn't working ?! finding first occurrence. what is wrong with it ? can't find the bug, copied almost identical code from the internet it worked but I need to know why my code isn't working
wrong: ``` mid=low+1;} … mid=high-1;} ``` right: ``` low=mid+1;} … high=mid-1;} ``` midchange is off the table.
My task is to build a matrix of order 2n with input. But when I'm trying to print it, something strange happens. Code: ``` #include<stdio.h> int main() { printf("Insert n: \n"); int n = 0; scanf("%d", &n); printf("Insert the elements of the matrix %d * ", 2*n); printf("%d\n", 2 * n); int mat[(2 * n) - 1][(2 * n) - 1]; for (int i = 0; i < 2 * n; i++) { for (int j = 0; j < 2 * n; j++) { scanf("%d", &mat[i][j]); } } for (int i = 0; i < 2 * n; i++) { for (int j = 0; j < 2 * n; j++) { printf("%d ", mat[i][j]); } printf("\n"); } return 0; } ``` Output: ``` Insert n: 1 Insert the elements of the matrix 2 * 2 1 2 3 4 1 3 3 4 ```
You are supposed to declare the 2d array withint mat[(2 * n)][(2 * n)]. The number inside squared bracket is the length of the array, not the maximum index.
If I have an enum type declaration in a recursive function, will it be 'created' multiple times? Does it work like '#define' in the sense that it just tells the pre-processor to 'swap' values (but with scope in mind)? What would happen here, per example: ``` void recuFun() { enum someEnum {UP, DOWN, LEFT, RIGHT}; // Initialized multiple times? /* ... */ recuFun(); } ``` I know that enum types aren't objects, and therefore won't be allocated to memory. but I'm not sure what's happening here, and as far as I know, it isn't a pre-processor 'swap' thing. it feels as if I'm wasting memory, or something like it.
Anenumdoesn't really exist at the assembly/machine code level; it's all integral values there. Declaring anenumortypedef enumin a recursive function will not use any more resources than declaring it in any other scope.
I want to grow an array at runtime (without predining the length with a macos) I have the following questions is it possible to do it with an array?If not shall I use a pointer to int? I tried the following code (and expecting012as output) but get000 ``` #include <stdlib.h> #include <stdio.h> int main() { int *arr = NULL; size_t n = 0; for (int i = 0; i < 3; ++i) { arr = realloc(arr, (n + 1) * sizeof *arr); arr[n++] = i; printf("%d", *arr); } } ```
OP's mostly has it. It is just printing the first element each time. ``` // printf("%d", *arr); printf("%d", arr[n-1]); ``` is it possible to do it with an array? No. In C an array cannot change size once it is defined. The memory size allocated and referenced by apointercan change though.
This question already has answers here:Constant pointer vs Pointer to constant [duplicate](8 answers)Closed7 months ago. I have a function that takes a pointer and I accidently declared it as a const. The function changes the pointer value (intentionally) - the actually pointer not the data that the pointer points to. I wondered why this does not create a warning.... ``` static void CalcCRC(const uint32_t *pData, uint8_t noWords) { // Do some other stuff.... pData = pData + noWords; // Do some other stuff.... } ```
The declarationconst uint32_t *pDatacreates a pointer to aconst uint32_t, meaning that what the pointer points to isconst, not the pointer itself, so modifying the pointer is legal. If you did something like this: ``` *pData = 0; ``` Then you would get an error for modifying aconsttype.
What does the type void(**)(void) mean? I came across this type in the example code. ``` static inline int wl_data_device_add_listener(struct wl_data_device *wl_data_device,const struct wl_data_device_listener *listener, void *data) {     return wl_proxy_add_listener((struct wl_proxy *) wl_data_device,                      (void (**)(void)) listener, data); } ```
void f(void)is a function taking no arguments and returning void.void (*p)(void)is a pointer to such a function.void (**pp)(void)is a pointer to such a pointer. Thenvoid (**)(void)is the type ofpp. Whether or not casting to this type in this situation is sensible is questionable.
I'm trying to compute a function using C program but getting an error. Code is as follows: ``` #include <stdio.h> #include <math.h> double VOLT_DIV(double t, double b); int main() { double formula, VBAT_CONVERT, SCALER, VCC; SCALER = 100.00; VCC = 3.30; formula = VOLT_DIV(30.02, 4.72); VBAT_CONVERT = ((formula)*(VCC)*(SCALER)); return VBAT_CONVERT; } double VOLT_DIV(double t, double b) { double c; c = (((t) + (b))/b); return c; } ``` I've modified type specifiers and format specifiers also added some headers after restarting the IDE i'm using. But no luck so far
What you return frommainis the exit status of the program. In this case, the result of the calculation. Anything other than a value of0as an exit status is by convention considered an error. I suppose you want to print the result instead, so use ``` printf("%f", VBAT_CONVERT); return 0; ```
for some odd reason when I run this code: ``` int func(int arr[],int n) { int a = *(&arr + 1) - arr; printf("%d",a); } ``` I get an address, and when I run the same code inside main I get the length of the array. any idea why? I ran it inside main and it gave me the length of an array, and when I ran it inside a function it gave me an address.
This function declaration ``` int func(int arr[],int n){ ``` is adjusted by the compiler to ``` int func(int *arr,int n){ ``` On the other hand. the array passed to the function as an argument expression is implicitly converted to a pointer to its first element of the typeint *. So within the function you actually deal with a pointer instead of an array. In any case the expression with pointers used in this line within the function ``` int a = *(&arr + 1) - arr; ``` is invalid and invokes undefined behavior.
I wrote a program that opens a diff file and is supposed to parse through the output. However, I can't even get to the parsing part of the algorithm. I decided to open the diff file in my main to troubleshoot what my first character in the stream is, and it doesn't match what is in the file. The first character in the file is '1', but when I run the code below, I get 49. I have no idea what has gone wrong. Can anyone guide me? Thank you in advance. ``` FILE *diff = fopen(diff_filename,"r"); int what; what = fgetc(diff); fprintf (stderr,"%d\n",what); ``` I tried to cast the output to a char variable, it still remains 49.
Yourfpritnf()format string is wrong. If you want a character representation it should be: ``` fprintf (stderr,"%c\n",what); ```
I'm currently stuck on this problem. I have thefollowing code: ``` int v[10] = {-1, 1000, 2}; int a; a = strlen((char *)v+1); printf("strlen result for (char *) v+1: %d\n", a); ``` I cannot undestand why the final result is always 5 on a little endian "machine". According to strlen documentation, the char * cast in this situation should return 4. I tried also in online compiler and other machines but the result remains the same. What am I missing ?
Most likely the bytes in V are represented as: ``` 0xff, 0xff, 0xff, 0xff, 0xe8, 0x03, 0x00, 0x00, ... ``` So after skipping the first byte (not the first int, since you cast to char *) there are 5 bytes before the first '\0' character.
I am programming C in Visual Studio Code, but I have this annoying problem. When Visual Studio Code automatically saves my work, it deletes the line that has the library inclusion that I need. So when I compile, it gives me an error that I did not specify the function. How can I resolve it?
You might have installed a corrupted version of Visual Studio Code or the library files of the Visual Studio Code and then location where you are saving your programs might be in different location. For example The library files of Visual Studio Code might be on the C: drive and the program files might be in anOneDrivefolder. Try reinstalling it from an authentic source if the second stated problem is not the case. If the problem still continues then please comment down on my reply. Reinstall either from Microsoft store or fromDownload Visual Studio Code.
I am trying to make a hamming code decoder and encoder in C and I cannot find a way to set the bits of a variable individually. For example, I am trying to somehow do the following: ``` #include "stdio.h" int main () { short block = 0010101110001110; // variable to contain the bits to decode } ``` Clearly this will not work but I am wondering if there is a way to do this or will I have to define it as the actual number this represents?
You can use hexadecimal representation, where each digit represents exactly 4 bits. ``` unsigned short block = 0x2b8e; ```
``` #include <stdio.h> int main() { char *a,*b; scanf("%s %s",a,b); printf("%s %s",a,b); return 0; } ``` It works like this, ``` #include <stdio.h> int main(){ char *a; scanf("%s",a); printf("%s",a); return 0; } ``` I think its something with memory becoz when i use malloc and assign some memory it works.
It is undefined behaviour (UB) in both cases as you pass the pointer which was not assigned with reference to the allocated valid memory, large enough to accommodate the scanned strings. As it is a UB it does not have to express itself in any particular way. So single variable version does not work as well. ``` int main(void) { char x[10], y[10]; char *a = x,*b = y; /* .... */ } ``` ``` int main(void) { char *a = malloc(10),*b = malloc(10); /* .... */ free(a); free(b); } ``` ``` int main(void) { char a[10], b[10]; /* .... */ } ```
I know the string in c will be terminated by a character\0. However, if I dochar a[5]="abcd\n", where would\0be? Or do I need to reserve at least one position for\0, whenever I try to usechar[]to store a string? Thank you for any help!
You should do: ``` char a[]="abcd\n"; ``` without specifying the size to let compiler figure out the buffer size. The actual buffer will have size of 6 to accommodate your 5 bytes + 1 byte for terminating zero. When you type "something" without assignment, compilaer puts that string in a dedicated place in the program with at least 1 zero byte after the last character. Writing char a[5]="abcd\n" is a bad practice because it will cause functions like strcpy() to act in undefined manner as your variable 'a' is not a c string, but just a buffer of characters, which by chance seem to be all printable/visible + terminating \n
Let's consider these two functions : ``` void my_foo1(char ** my_par, int size) { for (int i=0; i<size; i++) printf("%s \n",my_par[i]); } void my_foo2(int * my_par, int size) { for (int i=0; i<size; i++) printf("%d \n",my_par[i]); } ``` To call them, variables are declared and initialized. And after, function are called on a second line with these variables. ``` char * (my_strs[3])={"hello","world","!!!!"}; my_foo1(my_strs,3); int my_ints[3]={1,2,3}; my_foo2(my_ints,3); ``` Is it possible to write something like : ``` my_foox(????,3) ``` and avoid the variable declaration ?
It seems like what you're looking for is acompound literal: ``` my_foo1((char *[]){"hello","world","!!!!"},3); my_foo2((int []){1,2,3},3); ``` Note that such literals have the lifetime of their enclosing scope.
``` #define num 7 \\ user can change this #define size ???? \\I want this value (factorial of num) to be computed during compile time int array[size][num]; ``` I want to definearrayglobally, but its size is dependent on preprocessornum's value. So I want the value (factorial ofnum) to be determined at compile time. Is it possible? if yes, how?
In a separate .h file (for example fc.h): ``` #if num == 1 #define sum 1 #elif num == 2 #define sum 2 #elif num == 3 #define sum 6 #elif num == 4 #define sum 24 #elif num == 5 #define sum 120 #elif num == 6 #define sum 720 #elif num == 7 #define sum 5040 #elif num == 8 #define sum 40320 #elif num == 9 #define sum 362880 #else #error wrong number #endif ``` Usage ``` #define num 7 #include "fc.h" int array[sum][num]; ```
if (((number >> i) & 1) == 1) this is my code example. How is the return value determined in this operation? We shift numbers to the right or left. what is the return value? if (((number >> i) & 1) == 1)
number >> ibitwise-shiftsnumberto the right byibits: ``` number i number >> i ------ - ----------- 01010101 1 00101010 01010101 2 00010101 01010101 3 00001010 ``` etc. (number >> i) & 1does a bitwise-AND ofnumber >> 1against1: ``` 00101010 (01010101 >> 1) & 00000001 ---------- 00000000 00010101 (01010101 >> 2) & 00000001 ---------- 00000001 ``` So basically, ``` if (((number >> i) & 1) == 1) ``` will branch if the low bit of the shifted value is set.
I am trying to rewrite the code from AVR to STM32. How to translate this code into STM32? ``` #define READ_IO PIND & (1 << PD4) volatile unsigned char data_in = 0; data_in = (READ_IO) >> PD4; ``` I use STM32CubeIDE
Assuming pin4 on port D. ``` data_in = !!(GPIOD -> IDR & (1 << 4)); ```
I have written a simple makefile for compiling my C programs. I have amain.candfunctions.cfile. My makefile looks like this: ``` main : main.o functions.o gcc main.o functions.o -o main clean : rm *.o main ``` As you can see I haven't defined targets for main.o and functions.o, but still the executable file is generated when I runmake. Can you tell me why make utility didn't produce an error ?
GNU Make has acatalog of built-in rulesto build certain files from their dependencies. In this case, your dependencies main.o and functions.o are missing and it figures from the pattern rules that it build those from .c files. There is also a rule for linking so you should be able to just specify: ``` .PHONY: clean main: main.o functions.o clean: rm -f *.o main ``` Part of the value of make isstandard targets, so you should consider adding the ones that are relevant for your project.
I was reading from a file and writing it into an char* but the chars were not beeing saved after the array[96]. So I decided to run a simple check with this code: ``` int main(void){ char array[5]; memset(array, 0, sizeof(array)); array[1] = 'A'; array[2] = '\0'; printf("\n---%s---\n", array); return 0; } ``` I would expect ---A--- to be printed into the console, but the A is missing. Am I missing something?
The array index should start from 0. As Jonathan answered in the above comment, no need to set the terminatorarray[1] = '\0';since the array already got memset to 0. So the final code snippet will look like. ``` #include <stdio.h> #include <string.h> int main(void){ char array[5]; memset(array, 0, sizeof(array)); array[0] = 'A'; printf("\n---%s---\n", array); return 0; } ```