w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
  Home » C » Page 1
Line break replacing first value in char array
First off, you should not be using scanf, it is vulnerable for security attacks (http://en.wikipedia.org/wiki/Scanf_format_string, see security). With the format string %s, with no width specifier, you could effectively be overwriting the next variable in memory, if the name you enter is too long. So you should make sure that the format specifier should be something such as %19s, in NAME_LEN is 20

Categories : C

C pointer arithmetic palindrome
Why do you copy your pointer in another variable? int *ptr; ptr = &numArray[0]; Just send it to you function: palindrome(numArray); And sizeof(test) give you the memory size of a pointer, it's not what you want. You have to give the size in parameter of your function. int palindrome(int *test, int size){ ... } Finally your code must look like this: #include<stdio.h> int palin

Categories : C

How to detect CLOSE_WAIT on socket in C on Linux?
From man recv: Return Value These calls return the number of bytes received, or -1 if an error occurred. The return value will be 0 when the peer has performed an orderly shutdown.

Categories : C

Go TCP read is non blocking
Readers can return partial data. From the docs, "If some data is available but not len(p) bytes, Read conventionally returns what is available instead of waiting for more." (The sample code has a possibly unrelated but important problem: it throws away errors from the Read and Write. That could mask simple problems and make them very hard to debug. If you have problems after accounting for partia

Categories : C

Find biggest cluster in a 2D array
There are more memory-efficient methods, but: you can build another matrix with the same size and initialize it to all zeroes. Let this matrix be B. Start scanning first matrix, A, with a counter N initialized to 1, and as soon as you find in A a "1" that has a "0" in B (i.e. Aij = 1, Bij = 0), put it into a list and initialize M to 0. Then until the list is empty: pop an item from the list an

Categories : C

Virtual inheritance example in C, exploiting undefined behavior?
This program does indeed invoke undefined behavior, you have a violation of strict aliasing rules here: printf("%d ", Base_get_param((Base *) d)); ^^^^^^^^^ Strict aliasing rules make it undefined behavior to access an object through a pointer of a different type, although there is an exception for char* which we are allowed to use to alias without invoking undefi

Categories : C

Count how many field of an array are full
João Reis, You're using strcmp function to compare an integer element. The correct comparison may be: if ( juiz[i].num_juiz > 0 ) njuiz++; Maybe, if you want to use strcmp, you should change your data type to char *, like this: typedef struct { char nome[30]; char num_juiz[8]; } juiz; [Edit] In addition, you should look to your set up function, to be sure your data is beeing c

Categories : C

syntax error, expecting declaration seen while compiling C code for 8051 microcontroller
Each time you use any of your macros, it declares the same variable 'x' over and over. There's also no evidence that the compiler knows what sfir or sbit orsfr16 are.

Categories : C

malloc always allocate the same address
After you allocate your memory, you store the address into the variable s. Then you overwrite that value with the address of your name variable. As a result, you will never know the allocated address, because you discarded it with the overwriting.

Categories : C

Try_files if nginx module returns ngx_declined
Instead of trying to get a wobbly workaround, you should correct your C code, you are likely using the wrong nginx core method. You need to use ngx_parse_url instead of ngx_http_map_uri_to_path - like.

Categories : C

Type-Punning a pointer inside of incompatible but equivalent structs correctly
Neither snippet is portable. As for the first one, tmp's type is not compatible with that of the object pointed to by x, namely struct { int z; int *ptr; } or struct { int z; double *ptr; }. Thus dereferencing tmp is in violation of the strict aliasing rules. The problem with the second snippet is that having a union of pointers with incompatible types would only tell the compiler that the point

Categories : C

How do I deal with a data race in OpenMP?
Use reduction clause (description at MSDN). int* input = (int*) malloc (sizeof(int)*snum); int sum = 0; int i; for(i=0;i<snum;i++){ input[i] = i+1; } #pragma omp parallel for schedule(static) reduction(+:sum) for(i=0;i<snum;i++) { sum += input[i]; }

Categories : C

Arrays and Pointers, which is the better way to write in similar situations
When you use just a plain pointer, you still need to allocate memory for the array. We can do that with malloc! int *num,n,i; printf("Enter the value of n "); scanf("%d",&n); num = malloc(sizeof(*num) * n); printf("Enter the list of integers "); ... Also, even though you are using pointers, you can still write num[i] instead of *(num +i). In fact, those two expressions are always intercha

Categories : C

Where does this declaration come from: main _2a((argc,argv), int argc, char * argv[])
This macro is used to make K&R C-style function definition look more like "modern" C89 definitions. Expanded the code reads: main (argc,argv) int argc;char * argv[]; { ... } Or with a better indentation: main(argc, argv) int argc; char *argv[]; { ... } Which is an ancient way to write: int main(int argc, char *argv[]) { ... }

Categories : C

How Do you create an Linked lists of linked lists
You'll need a second structure, maybe like this: struct node_list { struct node *equation; struct node_list *next; }; The equation member hold a pointer to an equation (quadratic, list of struct node), while next points to the next struct node_list.

Categories : C

How to print out the address and content of each character in the input array
Thanks @chux for the clue, the completed code; #include "stdafx.h" #include <stdio.h> #include <string.h> void charAddresses(char *string); // 1st function to do int main() { int i = 0; char location[200] = "7825,CREEK VALLEY,SACRAMENTO,95828,CA"; //char *ptr; // 1. call function to print out the address and content of each character in the input array charAddr

Categories : C

Error in initializing the instance of a structure to NULL
tree *tree=NULL; // all the confusion is regarding this // the above is setting a pointer to NULL, which is ok *tree->root=NULL; // tried this one but it was wrong // the above is setting a // (not initialized to point to any specific memory) // offset in the tree struct variable // (that offset is not pointing any specific memory) // to set the first 4 bytes of that memory to NULL //

Categories : C

Macros in C language
If you want an implementation of sprintf that returns a string (instead of the character count), don't use a macro. Write a short function with a cyclic buffer of short strings instead: #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #define MAX_FMT 8 char *fmt(const char *format, ...) { static char buf[MAX_FMT][256]; static int nbuf; va_list va;

Categories : C

Fermat Primality Test failure in C
It looks like the main problem is caused by integer overflows in the modulo() function. Specifically, result=(result*b) is going to overflow quite regularly. You need to store these variables in 64-bit unsigned integers, and calculate the modulus of this result every time. This will work (with a few minor corrections elsewhere): #include <inttypes.h> #define MAXNUM 2000000000 #define MINN

Categories : C

Undefined reference to sem_init and other such functions even though -lpthread and -ltr are used
There are a few issues with this. First, instead of using pthread_t * for your variable types, you should only use pthread_t (i.e., not a pointer). This is what the warnings refer to. Second, the reason you're getting those linker errors is because the order in which you specify input files and linker options on the command line matters. Since rw.c depends on -lpthread, the -lpthread option shou

Categories : C

Zombie process even though threads are still running
The operating-system thinks your process is a zombie because the main thread, which was started by the operating-system, returned (i.e., exited). If you don't want this behavior, then don't have the main thread exit.

Categories : C

Find intersection in 2d arrays
try this #define min(x,y) ((x) < (y) ? (x) : (y)) void intersection(int *mat, int rows, int cols) { rows = min(rows, 5);//rows <--> cols cols = min(cols, 4); int ma2[] = { 0, 0, 1, 0, 1, // 1. Zeile 0, 0, 1, 0, 1, // 2. Zeile 0, 0, 1, 1, 0, // 3. Zeile 0, 0, 1, 0, 0 // 4. Zeile }; int i, j;

Categories : C

C function returns wrong int value
Your numbers are overflowing, your numbers are moste likely 32 or 64 bits signed integers here. Which means the maximum size can be 2^31=2147483648 or 2^63= 9223372036854775807. Just look at the size of the modexp(...) multiplied by m%n. That's quite a large number :) The same goes for modTemp * modTemp

Categories : C

Cleaning up linked list logic
Use fgets #define MAX_BUF_SIZE 1024 char temp[MAX_BUF_SIZE] = ""; do { fgets(temp, MAX_BUF_SIZE, stdin); addToStartOfList(l, temp) ; } while(strlen(temp) && (temp[strlen(temp) - 2] != '.'));

Categories : C

setwaitedtimer function does not invoke a callback function in c
why do you first set liDueTime.QuadPart=-100000000; which would fire the time 10 seconds after the call to SetWaitableTimer() and then qwDueTime = -5*1000; liDueTime.LowPart = (DWORD) ( qwDueTime & 0xFFFFFFFF ); liDueTime.HighPart = (LONG) ( qwDueTime >> 32 ); ? A negative due time of just 5000 100 ns units represents a relative delay of only 500 microseconds! Look at the MSDN

Categories : C

How to accept character array input into a structure in C?
change scanf("%s",&list[i].name); to scanf("%s",list[i].name);. Delete &. Because basically array name represents base address. No need to mention address of array for scanning the string.

Categories : C

cast 32bit-float to 64bit-double on system where sizeof double == sizeof float == 4
fixed denormals, infinites & nans unsigned __int64 Float2Double(float v) { unsigned int f = *(unsigned int*)&v; // reinterpret if ( !(f&0x7fffffff) ) return (unsigned __int64)f<<32; // return +/-0.0 unsigned int s = f>>31; // get sign unsigned int e = ((f&0x7f800000)>>23) -128; // get exponent and unbias from 128 unsigned int m = f&

Categories : C

Program crashing and returning code 255
You've said nothing about your platform and exit-codes are typically platform dependent. However a possible cause is (ironically) a stack overflow! Not only is that the name of this site but it's a real thing. All systems have a practical limit on recursion and to be honest 360 is a shed load of recursion. You might be able to modify the size of the stack in a compiler directive or option. If n

Categories : C

Value of pointer is different inside and outside the for-loop
Probably you are looking at the memory location where the loop variable i is stored (which value is 3 at that time). Note that you thereby enter the realm of undefined behavior. You are not allowed to access memory beyond the array's boundary. After the loop ended, the variable (that previously existed) at that very place was incremented one more time. Therefore you've observed a 4. Note that thi

Categories : C

Convert ngx_chain_t into buffer memory
Try fmemopen(3), read the man page 1st! Maybe I did not understand the question. But as I understood it, it was about replacing the fopen into something else the could read the inx_chain_t object structure like: ... fp = fmemopen(object, MAX, "r"); newLen = fread(source, sizeof(char), MAX, fp); ... Sorry if this still is a misunderstanding.

Categories : C

OpenWrt LibUbi implementation
The documentation is very thin on UCI. The way I figured it out is by using the uci_ptr's .value property from the uci structure. Fromt that, I change the line: ptr.o->v.string = "1"; to: ptr.value = "1"; I also changed your commit line as follows: uci_commit(ctx, &ptr.p, false); That worked for me.

Categories : C

gcc -O1 optimization slower than -O0
Okay it turns out that this occurs for version 4.8.1 of gcc, but not the later versions (is fixed with 4.8.3). For both the equivalent C and Fortran codes, using -O1 or higher caused the compiler to incorrectly optimise the code. To simplify the code, the incorrect result occurs from the lines: a = b - c; c = c + a; Which, if computed normally would be c = b + (c - c);, reducing to c = b;. But

Categories : C

Iverilog help combinational shift multiplier
I have created a version on EDA Playground which removes the tester and just runs a test program in the testbench. I have renamed the dump.dat to dump.vcd to work with EDA Playground. which should launch the wave form window when run. No real changes to the code other than moving test program to the testbench, and adding a second data point to the test vectors so they can be observed. otherwise

Categories : C

C - Get the number of digits in a double
You could try to find the shortest string that will yield your number when converted to a decimal floating-point number. The function below does this (provided you supply a sufficiently long char buffer) by repeatedly writing and scanning with increasing precision: char *strfloat(char buf[], int n, double d) { int p; for (p = 0; p < 20; p++) { double x; if (snprintf(b

Categories : C

Declare array but do not physically allocate it
You can define pointer to arrays: unsigned int (*PlaneSecondary)[_Lime_Y_res][_Lime_X_res] = (void*)_Lime_PPC_Base_; And then you can access it as: PlaneSecondary[layer][y][x]

Categories : C

Writing data to specific address during compile time
The address of things is determined at the linker stage and for the linker everything is just symbols. So while your gcc linker description file force symbol to be at specific address give an example for a function that equaly works for data. Define your version and put it in a seperate "version" section in the C code. Then the linker can place that section somewhere. Now the hard part is to get

Categories : C

Libcurl C - Save information Array
Take a look at CURLOPT_WRITEFUNCTION option of curl_easy_setopt(), and follow their examples. size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata); CURLcode curl_easy_setopt(CURL *handle, CURLOPT_WRITEFUNCTION, write_callback);

Categories : C

In socket, what happen if we take SOCK_STREAM as second and UDP as third argument in socket()?
The call would likely fail(socket() returns -1), and you can inspect errno to see why. On linux, this happens: $ cat t.c #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/socket.h> #include <netinet/in.h> int main(int argc,char argv[]) { int rc = socket(AF_INET, SOCK_STREAM, IPPROTO_UDP); printf("rc = %d errno = %d : %s ", rc, errno, strerr

Categories : C

shmctl and semctl do not remove the ipc
Please try to print out the shmid_ds structure using shmctl() with IPC_STAT as command. You can check the shm_nattch inside shmid_ds to see if it is 0 before you do the IPC_RMID. If it is not 0, it means that there are still some processes attached.

Categories : C




© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.