vendredi 29 mai 2015

Printing strings in linked lists

So I'm having trouble getting my program to print both the strings I input, or however many you want to put in the list, it always prints out the last string inputted multiple times. I am sorry about all the commented out code, most of it you don't need to read.

#include<stdio.h>
#include<stdlib.h>

struct node{
    char *data;
    struct node *next;
}*head;

typedef struct node NODE;

// Function prototypes
void append(char myStr[]);
void add( char myStr[] );
//void addafter(char myStr[], int loc);
void insert(char myStr[]);
int delete(char myStr[]);
void display(struct node *r);
int count();
// main function
int  main()
{
  int i;
  struct node *n;
  head = NULL;
  char myStr[50];

while(1)
{
    printf("\nList Operations\n");
    printf("===============\n");
    printf("1.Insert\n");
    printf("2.Display\n");
    printf("3.Size\n");
    printf("4.Delete\n");
    printf("5.Exit\n");
    printf("Enter your choice : ");

    if(scanf("%d", &i) <= 0)
    {
        printf("Enter only an Integer\n");
        exit(0);
    }
    else
    {

        switch(i)
        {

            case 1:
                printf("Enter the name to insert : ");
                scanf("%50s", myStr);
                insert(myStr);
                break;
            case 2:
                if(head == NULL)
                {
                    printf("List is Empty\n");
                }
                else
                {
                    printf("Name(s) in the list are : ");
                }
                display(n);
                break;
            case 3:
                printf("Size of the list is %d\n",count());
                break;
            case 4:
                if(head == NULL)
                    printf("List is Empty\n");
                else
                {
                    printf("Enter the myStrber to delete : ");
                    scanf("%50s",myStr);

                    if(delete(myStr))
                        printf("%s deleted successfully\n",myStr);
                    else
                        printf("%s not found in the list\n",myStr);
                }
                break;
            case 5:
                return 0;
            default:
                printf("Invalid option\n");
        }
    }
}

return 0;
}
// Function definitions
void append(char myStr[])
{
struct node *temp,*right;
temp = (struct node *)malloc(sizeof(struct node));
temp->data = myStr;
right=(struct node *)head;

while(right->next != NULL)
{
    right = right->next;
}
right->next = temp;
right = temp;
right->next = NULL;
}
// adding a node to the beginning of the linked list
void add( char myStr[] )
{
struct node *temp;
temp =(struct node *)malloc(sizeof(struct node));
temp->data = myStr;

// only one node on the linked list
if (head == NULL)
{
    head = temp;
    head->next = NULL;
}

else
{
    temp->next = head;
    head = temp;
}
}

void insert(char myStr[])
{
int c = 0;
struct node *temp;
temp = head;
if(temp == NULL)
{
    add(myStr);
}
else
{
        append(myStr);
}
}
int delete(char myStr[])
{
struct node *temp, *prev;
temp = head;

while(temp != NULL)
{
    if(temp->data == myStr)
    {
        if(temp == head)
        {
            head = temp->next;
            head = (*temp).next;
            free(temp);
            return 1;
        }
        else
        {
            prev->next = temp->next;
            free(temp);
            return 1;
        }
    }
    else
    {
        prev = temp;
        temp = temp->next;
    }
}
return 0;
}
void  display(struct node *r)
{
r = head;

if(r == NULL)
{
    return;
}

while(r != NULL)
{
    printf("%s ", r->data);
    r = r->next;
    if(r == NULL)
    {
        printf("\nOur linked list is finished!");

    }
}

printf("\n");
}
int count()
{
struct node *n;
int c = 0;
n = head;

while(n != NULL)
{
    n = n->next;
    c++;
}

return c;
}

modified bubble sort not showing the passes

My code is not showing the first pass when I entered the value 1,2,3,4,5 because of the

  • count condition which i have used. But i want my code to show at least 1 pass if it is in sorted order also.
  • stop the process if u find that the list is sorted in any intermediate point.

Here is my code:

#include<stdio.h>

int main()
{

    int s,i,j,temp,a[20],count=0,x,n=0;

    printf("Enter the number of elements :\n");
    scanf("%d",&s);

    for(i=0;i<s;i++)
    {
        printf("Enter element %d\n",i+1);
        scanf("%d",&a[i]);
    }
    printf("Unsorted list is :\n");
    for(i=0;i<s;i++)
    {
        printf("%d ",a[i]);
    }

    for(i=0;i<(s-1);i++)
    {
        count=0;
        n++;
        for(j=0;j<(s-i)-1;j++)
        {
            if(a[j]>a[j+1])
            {
                temp=a[j];
                a[j]=a[j+1];
                a[j+1]=temp;
                count++;
            }
        }

        if(count<=0)
        {
            break;
        }
        else
        {
            printf("\nAfter Pass %d elements are :",n);
            for(x=0;x<s;x++)
            {
                printf("%d ",a[x]);
            }
        }
    }

    printf("\nSorted list is :\n");
    for(i=0;i<s;i++)
        printf("%d ",a[i]);
    return 0;
}

Help me out guys,Your suggestion and idea would be very thankful to me.

OCaml - Compile OCaml and C code that uses Ctypes

I'm trying to learn how to call routines in C directly from OCaml code, using the Ctypes library.

I have this basic example with two files: hello.ml and hello.c.

hello.ml looks like this:

open Ctypes
open Foreign

let hello = 
    foreign "hello" (float @ -> returning void)
;;

let () = 
    hello 3.15
;;

hello.c looks like this:

#include <stdio.h>

void hello(double x)
{
    if ( x > 0)
        printf("hello!\n");
}

How do I compile these two files into one executable?

The process of manually compiling/linking code is scary to me and I don't understand it very well. I usually use a Makefile template to compile my code because that's really easy.

How do I copy numbers in string separated by space to an array in C [on hold]

If the string is "5 12 99 120 150 119". How can I copy these numbers in an array

fread() not working after fseek() with fwrite() in C

In my program i make a binary file contains structs (each struct contains one integer)...and i put 3 structs in the file...i want first to create the file...then close it..then reopen it as "rb+" mode...and i want to read the structs from the file and change its value (member data) and rewrite it at the same file as this way:

#include <stdio.h>
main()
     {
         int i;

         struct
         {
             int data;
         }x;  

         FILE* myfile=fopen("d:\\text.bin","wb");

         for(i=1;i<4;i++)
         {
              x.data=i;
              fwrite(&x,sizeof(x),1,myfile);
         }

         fclose(myfile);

         myfile=fopen("d:\\text.bin","rb+");

         for(i=0;i<3;i++)
         {
              fread(&x,sizeof(x),1,myfile);
              printf("%d\n",x.data);
              fseek(myfile,-sizeof(x),SEEK_CUR);
              x.data=2*x.data;
              fwrite(&x,sizeof(x),1,myfile);
         }

         fclose(myfile);

     }`

but...my output in stdout file was: 1 2 2

it should be 1 2 3

BUT...when i added fseek(myfile,0,SEEK_CUR); after fwrite(&x,sizeof(x),1,myfile);....it is run correctly and output : 1 2 3

can any one help me ???

POSIX req'ts for sendmsg() SCM_RIGHTS with some but not all fds invalid

Does POSIX, or any other relevant standard, mandate any particular behavior when one or more (but not all) of the file descriptors being sent across an AF_UNIX socket with sendmsg() are invalid?

Concretely, the test program at the end of this question (apologies for its length) attempts to send an array of file descriptors over a socket, one of which may be deliberately initialized to -1 rather than a valid file descriptor. Linux (kenel 3.13), NetBSD (6.1.5), and OSX (10.10) all agree that if any of the descriptors are invalid, the sendmsg call fails, with errno set to EBADF. I would like to know if this is actually standard-required behavior, and (regardless) whether any other Unix implementations behave differently. The only thing I was able to find in the online copy of SUSv7 regarding SCM_RIGHTS messages was a requirement that the constant be defined:

The <sys/socket.h> header shall define the following symbolic constant for use as the cmsg_type value when cmsg_level is SOL_SOCKET: SCM_RIGHTS: Indicates that the data array contains the access rights to be sent or received.

(Abstractly, it would seem more useful for the call to succeed when at least one of the file descriptors is valid, and for the receiving process to get an array of the same length and ordering as was sent, with all invalid entries forced to -1.)

(When invoked with no arguments, the test program sends an array of two fds, both of which are valid. When invoked with a single argument, which must be the single character 0, 1, or 2, the test program sends an array of three fds, and the slot in the array corresponding to the value of the argument is set to -1, whereas the other two are set to valid fds. This confirms that the receive-side code works, and demonstrates that the kernel behavior does not depend on the position of the invalid fd within the array.)


#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>

static void
describe_fds(int nfd, int fds[], const char *tag)
{
  struct stat st;
  int i;

  printf("%s: nfd=%d: ", tag, nfd);
  if (nfd < 0) nfd = 0;

  for (i = 0; i < nfd; i++) {
    if (i > 0)
      fputs("; ", stdout);

    if (fstat(fds[i], &st))
      printf("[%d] = %d (%s)", i, fds[i], strerror(errno));
    else
      printf("[%d] = %d (%ld)", i, fds[i], (long) st.st_ino);
  }
  putchar('\n');
}

static void
do_receive_fds(int sk, int xnfd)
{
  char dummy[1];
  int *fds, nfd, got_fds = 0;
  ssize_t n;
  struct iovec iov[1];
  struct msghdr msg;
  struct cmsghdr *cmsg;
  char *cmsgbuf = malloc(CMSG_SPACE(sizeof(int) * xnfd));

  if (!cmsgbuf) {
    printf("R: malloc: %s\n", strerror(errno));
    return;
  }

  iov[0].iov_base    = &dummy;
  iov[0].iov_len     = 1;

  msg.msg_name       = 0;
  msg.msg_namelen    = 0;
  msg.msg_iov        = iov;
  msg.msg_iovlen     = 1;
  msg.msg_control    = cmsgbuf;
  msg.msg_controllen = CMSG_SPACE(sizeof(int) * xnfd);
  msg.msg_flags      = 0;

  n = recvmsg(sk, &msg, MSG_WAITALL);
  if (n < 0) {
    printf("R: recvmsg: %s\n", strerror(errno));
    return;
  }
  printf("R: recieve flags = %x\n", (unsigned) msg.msg_flags);
  if (n == 0)
    puts("R: short read ordinary data");
  else
    printf("R: ordinary data = %02x\n", (unsigned char)dummy[0]);

  for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
    if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) {
      printf("R: unexpected cmsg %d/%d\n",
             cmsg->cmsg_level, cmsg->cmsg_type);
      continue;
    }
    nfd = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
    if (cmsg->cmsg_len < CMSG_LEN(sizeof(int) * xnfd))
      printf("R: short read ancillary data (exp %lu/%d got %u/%d)\n",
             CMSG_LEN(sizeof(int)*xnfd), xnfd, cmsg->cmsg_len, nfd);

    fds = calloc(nfd, sizeof(int));
    if (!fds) {
      printf("R: calloc: %s\n", strerror(errno));
      continue;
    }

    memcpy(fds, CMSG_DATA(cmsg), nfd * sizeof(int));
    got_fds = 1;
    describe_fds(nfd, fds, "R");
    free(fds);
  }
  if (!got_fds)
    puts("R: no fds received");

  free(cmsgbuf);
}

static int
do_send_fds(int sk, int nfd, int *fds)
{
  char dummy[1];
  ssize_t n;
  int err;
  struct iovec iov[1];
  struct msghdr msg;
  struct cmsghdr *cmsg;
  char *cmsgbuf;

  if (nfd < 0) nfd = 0;

  cmsgbuf = malloc(CMSG_SPACE(sizeof(int) * nfd));
  if (!cmsgbuf) {
    printf("S: malloc: %s\n", strerror(errno));
    return 1;
  }

  dummy[0]           = 'X';
  iov[0].iov_base    = &dummy;
  iov[0].iov_len     = 1;

  msg.msg_name       = 0;
  msg.msg_namelen    = 0;
  msg.msg_iov        = iov;
  msg.msg_iovlen     = 1;
  msg.msg_control    = cmsgbuf;
  msg.msg_controllen = CMSG_SPACE(sizeof(int) * nfd);
  msg.msg_flags      = 0;

  cmsg               = CMSG_FIRSTHDR(&msg);
  cmsg->cmsg_level   = SOL_SOCKET;
  cmsg->cmsg_type    = SCM_RIGHTS;
  cmsg->cmsg_len     = CMSG_LEN(sizeof(int) * nfd);

  memcpy(CMSG_DATA(cmsg), fds, sizeof(int) * nfd);

  n = sendmsg(sk, &msg, 0);
  err = errno;
  free(cmsgbuf);

  if (n < 0) {
    printf("S: sendmsg: %s\n", strerror(err));
    return 1;
  }
  if (n == 0) {
    puts("S: sendmsg: short write");
    return 1;
  }
  return 0;
}

static int
child_task(int sk, int xnfd)
{
  do_receive_fds(sk, xnfd);
  return 0;
}

static int
parent_task(int sk, pid_t pid, int loc)
{
  FILE *a, *b;
  int fds[3];
  int status;
  int nfd;

  a = tmpfile();
  if (!a) {
    printf("S: tmpfile A: %s\n", strerror(errno));
    goto fail;
  }
  b = tmpfile();
  if (!b) {
    printf("S: tmpfile B: %s\n", strerror(errno));
    goto fail;
  }

  switch (loc) {
  case 0: nfd = 2; fds[0] = fileno(a); fds[1] = fileno(b); fds[2] = -1; break;
  case 1: nfd = 3; fds[0] = fileno(a); fds[1] = fileno(b); fds[2] = -1; break;
  case 2: nfd = 3; fds[0] = fileno(a); fds[1] = -1; fds[2] = fileno(b); break;
  case 3: nfd = 3; fds[0] = -1; fds[1] = fileno(a); fds[2] = fileno(b); break;
  default:
    printf("S: impossible: loc=%d\n", loc);
    goto fail;
  }

  describe_fds(nfd, fds, "S");
  fflush(0);

  if (do_send_fds(sk, nfd, fds))
    goto fail;

  if (waitpid(pid, &status, 0) != pid) {
    printf("S: waitpid: %s\n", strerror(errno));
    return 1;
  }
  if (status != 0) {
    printf("S: abnormal child exit status %04x\n", (unsigned short)status);
    return 1;
  }
  return 0;

 fail:
  kill(pid, SIGKILL);
  waitpid(pid, &status, 0);
  return 1;
}

int
main(int argc, char **argv)
{
  int skp[2];
  pid_t pid;
  int loc, xnfd;

  if (argc == 1) {
    xnfd = 2;
    loc = 0;
  }
  else if (argc == 2 && argv[1][1] == '\0') {
    xnfd = 3;
    switch (argv[1][0]) {
    case '0': loc = 3; break;
    case '1': loc = 2; break;
    case '2': loc = 1; break;
    default: goto usage;
    }
  } else {
  usage:
    fprintf(stderr, "usage: %s [0|1|2]\n", argv[0]);
    return 2;
  }

  if (socketpair(PF_LOCAL, SOCK_STREAM, 0, skp)) {
    perror("socketpair");
    return 1;
  }

  fflush(0);
  pid = fork();
  if (pid == -1) {
    perror("fork");
    return 1;
  }
  if (pid == 0) {
    return child_task(skp[0], xnfd);
  } else {
    return parent_task(skp[1], pid, loc);
  }
}

Single large function vs multiple smaller funcions?

I am well aware of fact that single task per function is better than single function doing multiple tasks. Moreover, my question is bit trickier than this.

I am writing a parser which requires many parameters (8 to 10) on various condition to parse a input buffer. I have following two choices.

  1. Keep all functions small enough including main parser function. Pass the required parameters as pointer to structure from the main parser function to helper functions. Individual Function will access parameter from structure and write the result to the structure.

  2. One large main parser function (~250 lines) and other smaller functions. All required parameters will be local to main parser function. Main function pass the parameters to helper functions by arguments. function arguments are limited to 4 only.

Which is the better approach?

When does fwprintf return a negative number?

I couldn't find it in the docs anywhere, all I did find was that it returns a negative number when an error occurs. What error can it be?

The error occurs in a function that looks like this:

void foo(wchar_t** a)
{
    for (int i = 0; i < N; i++)
        if (fwprintf(stderr, L"%ls ", a[i]) < 0)
            puts("OOPS!");
    fwprintf(stderr, L"\n");
}

Also, this error appears only at one point during the program execution and stays there, as if some kind of limit was reached.

String literals vs array of char when initializing a pointer

Inspired by this question.

We can initialize a char pointer by a string literal:

char *p = "ab";

And it is perfectly fine. One could think that it is equivalent to the following:

char *p = {'a', 'b', '\0'};

But apparently it is not the case. And not only because the string literals are stored in a read-only memory, but it appears that even through the string literal has a type of char array, and the initializer {...} has the type of char array, two declarations are handled differently, as the compiler is giving the warning:

warning: excess elements in scalar initializer

in the second case. What is the explanation of such a behavior?

fgets() creating another copy of string at time of input?

I'm wondering what the error is here? I'm making a causer cipher, and it works fine but when I print the encrypted message at the end, it reprints the unencrypted message. When I comment out and set message to a sentence, it works fine. But when I get a string using fgets it creates another copy. Thanks in advance!

 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <ctype.h>

int main(int argc, char *argv[]) 
{
    char message[100];  
    printf("Please Enter a message to be Encrypted: ");
    fgets(message, 100, stdin);
    unsigned char caeser[] = "";
    int j = 0;
    if(argc >= 2)
    {
    int k = atoi(argv[1]);
    for(int i = 0, n = strlen(message); i < n; i++)
    {
        printf("%i\n",n);
        if(!isspace(message[i]))
        {
            if(islower(message[i]))
            {
                j = message[i] - 97;
                caeser[i] = 97 + ((j + k) % 26);
            }
            if(isupper(message[i]))
            {
                j = message[i] - 65;
                caeser[i] = 65 + ((j + k) % 26);
            }
        }   
        else
        {
            caeser[i] = ' ';
        }
       }
    printf("%s\n", caeser);
    }
}

output of this c program is weird ,instead of value -4 at second position third line it shows -5 how?

#include<stdio.h>
int main()
{
    int a=5,b=9;
    char ch='c';
    printf("%c %c\n",ch,++ch);
    printf("%d %d\n",a,!!a);
    printf("%d %d %d\n",a=a+2,-a + ++b%a,a<<2);//
    printf("%d",a);
    return 0;
}



/* 
    op
    d d
    5 1
    7 -5 20
    7
*/

output of this c program is weird ,instead of value -4 at second position third line it shows -5 how? i am using devc++IDE

Compare string element to ASCII value

I am writing a C program for my exam and i am facing some issues. For example, in an this exercise :

    char y = 'a';

    if (y >= 65)
        printf("MAJOR");

or :

    char a[] = "bare";

    if (a[0] >= 65)
        printf("MAJOR");

I would really like to get MAJOR printed but I always get an error.

My aim is to see if an element of my char array is major or equals to a specified ASCII value (65 is 'A').

Also I got a pointer that actually needs to move in the char array: how can I scroll it trough until '\0' ?

I tried with :

    for (i = 0 ; &p->info[i] != '\0' && &s[i] != '\0'; i++)
                         // the info field of this struct is type char *

Where info is char* and s is char s[].

Is this for loop fine?

EDIT: NEW ISSUE

Guys it's really weird i got a generic error trying to run just this line of code:

    char y = 'a';

Seems that my 'y' variable is filled with an underscore instead of 'a'....? I'm using Xcode right now

After getting input string from the user, output includes some other character(s)

I decelerate a matrix of chars

char strs[3][200] = {'\0'};

and then try to insert string just for the first row

gets(strs[0]);

and then try to print all the rows

printf("1) ");
puts(strs[0]);
printf("2) ");
puts(strs[1]);
printf("3) ");
puts(strs[2]);

The result is

1) ☺me input from the user
2) ☺
3) ☺

why there is a "smiley" in the result ☺?

How to create empty char arrays in Cython without loops

Well, this seems easy, but I can't find a single reference on the web. In C we can create a char array of n null-characters as follows:

char arr[n] = "";

But when I try to do the same in Cython with

cdef char arr[n] = ""

I get this compilation error:

Error compiling Cython file:
------------------------------------------------------------
...
cdef char a[n] = ""
                   ^
------------------------------------------------------------

Syntax error in C variable declaration

Obviously Cython doesn't allow to declare arrays this way, but is there an alternative? I don't want to manually set each item in the array, i.e. I'm not looking for something like this

cdef char a[10]
for i in range(0, 10, 1):
    a[i] = b"\0"

How to compile with c11 standard library on OS X with clang?

Hey I am trying to compile c code that uses functions from the c11 standard library on OS X with clang.

The compiler option -std=c11 allows me to use c11 language features. But when I am using new functions like at_quick_exit I get the following warning implicit declaration of function 'at_quick_exit' is invalid in C99.

The source code has the following line #include <stdlib.h> The clang option -stdlib does not help.

My Systems:

OS X Yosemite 10.10.3

$ clang -v
Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.3.0
Thread model: posix

Ubuntu 14.04 LTS

$ clang -v
Ubuntu clang version 3.4-1ubuntu3 (tags/RELEASE_34/final) (based on LLVM 3.4)
Target: x86_64-pc-linux-gnu 
Thread model: posix

To be more explicit. How can I get on OS X a c11 standard library?

Thanks for any kind of help.

What is meant by "compiler helps implement the C standard?"

I am reading / studying the book: Linux System Programming: Talking Directly to the Kernel and C Library and quoting from this book:

The compiler used in a Unix system—Linux included—is highly relevant to system programming, as the compiler helps implement the C standard and the system ABI.

What is meant by compiler helps implement the C standard ?

What is the name of CMake's default build target?

I have a custom target, and I want it to depend on the default target (the one that is built with make).

add_custom_target(foo ....)
add_dependency(foo default_target_name_goes_here)

What is the name of the default target?

I've tried ALL, ALL_BUILD, MyProjectsName, DEFAULT,...

Finding anything in the CMake documentation is always an unsuccessful adventure...

Hardware options for simple image processing

I need to choose a hardware configuration which will be responsible for simple image processing task. The task which I want to be performed is:

  1. Wait for an external synchronization signal. This may be a GPIO signal (primary option) or network signal from NTP server;
  2. Take image data from camera;
  3. Processing: as minimum, threshold image and make binary matrix; as maximum - detect blobs and find their centers;
  4. Send away resulting matrix (or blob's centers);
  5. Goto 1.

Constraints:

  • Performance: results should be sent away at least once per second. 10-30 FPS would be optimal. Higher rate (90-120 FPS) would be ideal finite result :)
  • Budget: 100$ max.

It seems that embedded systems are only ones which could fit the budget constraint. So far I found these options (sorted on price):

  • Cheap smartphone with root access, e.g. Elephone G2 for 99$. Most expensive option. With network and OpenCL support it might do the job with lowest amount of low level stuff to be learned (and thus faster development time), but it costs a lot.

  • 25$ Raspberry Pi (Model A) + 15$ RasPi camera module.

  • C.H.I.P. - this is a recently announced 9$ alternative for RPi which is not available at the moment (29/05/2015).

  • 4$ STM32 board (4$ for Stm32f103c8t6 on aliexpress.com) + 4$ for OV7670 camera module.

Are there any other options which I've failed to find?

I need the cheapest option which will meet time constraint. By default I think to choose Raspberry Pi because I'm sure it will be fast enough since it has fast camera interface, allowing streaming VGA in 90 fps (without processing though). But is still costs 40$ at least, and there is cheaper STM32 option which costs 4 times less. So the question is: will it be enough to use STM32 board?

I think, that since this board has DMA (can read from camera without needing processor) and running on 72 MHz, it might suffice, but I don't know for sure, and don't know how to estimate minimum frequency required for this task.

Also, I found relevant question:

Relevant microcontroller specs for (very) simple image processing

But it didn't help me to figure out if this cheap stm32 board will suffice. It has 64K flash, so it won't be possible to read full image from the camera at once, but that's not necessary, since data may be read by chunks from camera's FIFO buffer and processed sequentially (AFAIK)

Thanks.

Interesting GCC Linking

I was playing around with symbols and function pointers recently and noticed that though the following code runs fine:

#include <stdio.h>
int main(int argc, const char * argv[]) {
    printf("%p\n",printf); // <--this line makes it work
    int (*printfptr)(const char * restrict, ...);
    printfptr = 0x1001fe910;
    (*printfptr)("Hello world\n");
    return 0;
}

This does not:

#include <stdio.h>
int main(int argc, const char * argv[]) {
    // printf("%p\n",printf); // <-- commenting this out breaks it
    int (*printfptr)(const char * restrict, ...);
    printfptr = 0x1001fe910;
    (*printfptr)("Hello world\n");
    return 0;
}

(EXC_BAD_ACCESS)

How come dereferencing the exact same pointer causes issues when there is no reference to printf in the code? Even this works fine:

#include <stdio.h>    
int main(int argc, const char * argv[]) {
    int (*printfptr)(const char * restrict, ...);
    printfptr = 0x1001fe910;
    (*printfptr)("Hello world\n");
    return 0;
}
void *_ = printf; // <-- because of this

Why is this?

Using realloc for dynamic array Array **

(C question) Hi, I tried to extend my fully list of players. When i use the realloc function, it save my first player but not any other of the list. I mean that in the and of the realloc i got just one (Player *pl) in the list. this is part of the function:

void initializeListForTree(Player** players, int listSize)
{
    int formulaSize = bla bla bla.....
    players = (Player **)realloc(players, sizeof(Player *)*formulaSize);
    if (!players)
    {
        printf("memory allocation failed\n");
    }
}

C - char array and char pointer

Why I can't define

char **pp={ "123", "456", "789" };

But I can defined it as a char*[] ,and send it to a function that will acsept it as a char **

char *pp[]={ "123", "456", "789" };
fun(pp);

void fun(char **pointerToPointer)
{
    //++(**pointerToPointer);//error
    printf("%s", *pointerToPointer); 
}
//output::"123"

And why I can't increment

++(**pointerToPointer);

Forced to define Go struct for casting an unsafe.Pointer() to a C struct

Interoperating with C code, I was not able to directly cast a structure and I was forced to define an equivalent one in Go. The C function from libproc.h is

int proc_pidinfo(int pid, int flavor, uint64_t arg,  void *buffer, int buffersize)

The C structure for flavor==PROC_PIDTASKINFO is proc_taskinfo as defined in sys/proc_info.h (included by libproc.h):

struct proc_taskinfo {
    uint64_t        pti_virtual_size;   /* virtual memory size (bytes) */
    uint64_t        pti_resident_size;  /* resident memory size (bytes) */
    uint64_t        pti_total_user;     /* total time */
    uint64_t        pti_total_system;
    uint64_t        pti_threads_user;   /* existing threads only */
    uint64_t        pti_threads_system;
    int32_t         pti_policy;     /* default policy for new threads */
    int32_t         pti_faults;     /* number of page faults */
    int32_t         pti_pageins;        /* number of actual pageins */
    int32_t         pti_cow_faults;     /* number of copy-on-write faults */
    int32_t         pti_messages_sent;  /* number of messages sent */
    int32_t         pti_messages_received;  /* number of messages received */
    int32_t         pti_syscalls_mach;  /* number of mach system calls */
    int32_t         pti_syscalls_unix;  /* number of unix system calls */
    int32_t         pti_csw;            /* number of context switches */
    int32_t         pti_threadnum;      /* number of threads in the task */
    int32_t         pti_numrunning;     /* number of running threads */
    int32_t         pti_priority;       /* task priority*/
};

Even if Go code actually works, I was not able to use C.proc_taskinfo directly. The Go function is propertiesOf(): complete source here.

If I reference the C structure, I got a similar error reported as in my latest question on the subject: could not determine kind of name for C.proc_taskinfo, but this time I'm sure the definition is imported with #include.

Unkown type name "Enemy" error after including all headers in C

I'm developing a game with SDL 2.0 in C and I have the following problem: After including all the needed .h files on each file, the compiler shows an error (unknown type name 'Enemy') on shoots.h, where I have a function with a parameter of type Enemy declared on enemy.h.

The header files where I think I'm getting the error are bullet.h, enemy.h, mobs.h, and shoots.h. (There are more like sdl.h)

bullet.h

#ifndef BULLET_H_INCLUDED
#define BULLET_H_INCLUDED
#include "sdl.h"

typedef struct Bullet *Bullet;

#endif // BULLET_H_INCLUDED

enemy.h

#ifndef ENEMY_H_INCLUDED
#define ENEMY_H_INCLUDED
#include "sdl.h"
#include "shoots.h"

typedef struct Enemy *Enemy;

#endif // ENEMY_H_INCLUDED

mobs.h

#ifndef MOBS_H_INCLUDED
#define MOBS_H_INCLUDED
#include "enemy.h"

typedef struct EnemyList *EnemyList;
typedef struct EnemyPosition *EnemyPosition;

#endif // MOBS_H_INCLUDED

shoots.h

#ifndef SHOOTS_H_INCLUDED
#define SHOOTS_H_INCLUDED
#include "sdl.h"
#include "player.h"
#include "bullet.h"
#include "enemy.h"


typedef struct BulletList *BulletList;
typedef struct BulletPosition *BulletPosition;

void initEnemyShoots(BulletList l, BulletPosition p, Player pl, Enemy e);

#endif // SHOOTS_H_INCLUDED

struct Enemy declaration on enemy.c

struct Enemy {
    SDL_Surface *sprite;    //Enemy sprite
    int x, y;             //Enemy position
    int w, h;               //Enemy hitbox
    BulletList ammo;      //Enemy bullets
};

Those headers also have the declaration of functions implemented on each .c file. All structs are defined on his own .c

That initEnemyShoots is where I have the problem, since one of it's parameters is type Enemy. How can I solve that?

nasm, macro print not working

I'm calling a function written in assembly from a C file. The c code passes two pointers to the assembly function. I'm using the print macro into the assembly to check the value of the addresses and of the elements pointed by them.

Here is the C code:

extern int nn_from_set(float *q, float *t, int q_length, int *s, int s_length);

int main()
{
    float *matrix_dyn = malloc(6*4*sizeof(float));
    int *s = malloc( 3 * sizeof(int))
    //the vectors are filled here
    //print their address, no problem here
    printf("t: %p, s: %p, sizeof int*: %u\n", matrix_dyn, s,  sizeof(matrix_dyn));
    //assembly function called
    printf("Prova: %d\n", nn_from_set(matrix_dyn, matrix_dyn, 3, s, 3));
    return 0;
}

Here is the assembly code, it's a bit long.

extern printf

%macro pabc 1           ; a "simple" print macro
section .data       
.strm db %1,0            ; %1 is first actual macro call

section .text

    ; push onto stack bacwards
    push dword [nnfs_int]                ; int a
    push dword .strm
    push dword nnfs_fmt_int              ; users string
    call printf                          ; call C function
    add esp, 12                           ; pop stack 3 * 4 bytes

%endmacro

    section .data
fmt: db "%s, dist: %e",10,0         ; format string for printf
nnfs_fmt: db "%s",10,0              ; format string for printf
nnfs_fmt_int:   db "%s %p",10,0     ; format string for int debug


    section .bss

nnfs_dst:   resd 1                  ; reserve 32-bit word
nnfs_tmp:   resd 1                  ; int tmp;
nnfs_index: resd 1                  ; reserve 32-bit, int index;  
nnfs_int:   resd 1

    section .text

; function to be translated is 
; int nearest_neighbor_from_set(float* q, float* t, int q_length, int* s, int s_length)

global nn_from_set

nnfs_q           equ     8
nnfs_t           equ     12
nnfs_q_length    equ     16
nnfs_s           equ     20
nnfs_s_length    equ     24

nn_from_set:
            ; -------------------------------------------
            ; Entrace sequence
            ; -------------------------------------------
            push    ebp         ; save base pointer
            mov     ebp, esp    ; point to current stack frame
            push    ebx         ; save general registers
            push    esi         
            push    edi

            mov ecx, [ebp + nnfs_t]     ; t
            mov edx, [ebp + nnfs_s]     ; s

            mov [nnfs_int], ecx         ; print t
            pabc "ecx, t: " 

            mov [nnfs_int], edx        ; print s 
            ;pabc "edx, s: "

            mov esi, [edx]              ; *s

            mov [nnfs_int], esi         ; print *s
            ;pabc "edx"

            add edx, 4
            mov esi, [edx]

            mov [nnfs_int], esi
            ;pabc "esi"

            ; fine di nn_from_set
            mov eax, 50         ; for test purpose

            ; ------------------------------------------
            ; Exit sequence
            ; ------------------------------------------

            pop     edi
            pop     esi
            pop     ebx
            mov     esp, ebp
            pop     ebp
            ret

I have two problems, with this version of the code, when I try to compile, it says that .strm is already defined, it does each time I try to call the macro after the first call.

Second problem. I change the macro like this:

 %macro pabc 1           ; a "simple" print macro

section .text

    ; push onto stack bacwards
    push dword [nnfs_int]                ; int a
    push dword nnfs_fmt_int              ; users string
    call printf                          ; call C function
    add esp, 8                           ; pop stack 2 * 4 bytes

%endmacro

I've removed the .strm argument. The format string is now:

nnfs_fmt_int:   db " reg %p",10,0

With this version, the first call of the macro prints correctly, the second goes wrong. For example, I call the macro to print the addresses of the two pointers:

mov [nnfs_int], ecx         ; print t
pabc "ecx, t: " 

mov [nnfs_int], edx        ; print s 
pabc "edx, s: "

Here is the output (the first line is printed from the C file):

t: 0x8500008, s: 0x8500070, sizeof int*: 4
 reg 0x8500008
 reg 0xf7778898

Address of t is printed correctly, s's one, not. If I invert the two calls.

mov [nnfs_int], edx         ; print s
pabc "ecx, t: " 

mov [nnfs_int], ecx        ; print t
pabc "edx, s: "

This is the output (the first line is printed from the C file):

t: 0x93a0008, s: 0x93a0070, sizeof int*: 4
 reg 0x93a0070
 reg (nil)

S is printed right, but t isn't.

I have no idea what is going wrong, I have used the same macro pattern and it hasn't created me any problem until now. The examples tha I used to create this macro are from here: http://ift.tt/1SGA5bO

Sorry for the long question, and thank you in advance for any help.

splint large project (hundreds of files)

I'm using splint for a moderately large project. All is fine, but we are now trying to up the level from "weak" to "checks". Because we are checking files one by one splint complains about undefined functions. I seem to remember splint had the option to analyse multiple files individually and then do a final analysis of all together (compile + link style).

I don't find any info on how to do this in the manual nor general Googling.

Is this possible?

Thanks,

Reading binary file to a string but the types are mixed

I'm trying to read a binary file but when I read its characters it doesn't looks like it's formatted with char type so for example the numbers don't have their ASCII value instead, their actual value but letters does have ASCII value.

Why is that?

Also, when I create a binary file, it doesn't hold all those '\0' padding, nor the \x behind every number, what are those and why do they show up?

This is how I'm reading the file:

FILE * fp = fopen("file.bin", "rb");
char foo[20];
fread(foo, sizeof(char), 20, fp);

Which I can see in VS, fills foo with this:

[0]: 5 '\x5'
[1]: 0 '\0'
[2]: 0 '\0'
[3]: 0 '\0'
[4]: 97 'a'
[5]: 66 'B'
[6]: 67 'C'
[7]: 100 'd'
[8]: 101 'e'
[9]: 6 '\x6'
[10]: 0 '\0'
[11]: 0 '\0'
[12]: 0 '\0'
[13]: 97 'a'
[14]: 97 'a'
[15]: 66 'B'
[16]: 84 'T'
[17]: 82 'R'
[18]: 121 'y'
[19]: 4 '\x4'

Is there a way to read all characters such that all will hold ASCII values? Is there a way to not read the \0 and \x?

zeromq Paranoid Pirate performance

I'am currently developing a system with a server, which gets tasks of some clients and processes them. As i need high throughput i examined the speed for roundtrips/s. I use the Paranoid Pirate mode which zguide said.

Clients have a Dealer socket and send a task to the server, server receives the tasks with a Router socket (TCP-Connection) The server fowards the Tasks to one Worker-process (Router - Dealer via Tcp) The worker processes the tasks and sends the response back on the same way.

I get only 20000 RT/s. cpu occupancy rate 80%, client 90%, worker80%. My test machine has 4 core cpu and 8g memory. Please help me what's the wrong thing i have make. Thanks

client code:

void * client ()
{
    zctx_t *ctx = zctx_new ();
    void *client = zsocket_new (ctx, ZMQ_DEALER);

    //  设置随机标识,方便跟踪
    char identity [10];
    sprintf (identity, "%04X-%04X", randof (0x10000), randof (0x10000));
    zsocket_set_identity (client, identity);
    zsocket_connect (client, "tcp://localhost:5755");

    zmq_pollitem_t items [] = { { client, 0, ZMQ_POLLIN, 0 }, { client, 0,      ZMQ_POLLOUT, 0 } };
    uint64_t start = zclock_time ();
    uint64_t start2 = zclock_time ();
    while (1) {
        int64_t more = 0;
        if (zmq_poll (items, 2, ZMQ_POLL_MSEC) == -1)
        {
            break;
        }

        if (items [0].revents & ZMQ_POLLIN) 
        {
            static int nTmp = 0;
            if (++nTmp % 100000 == 0)
            {
                printf("recv 100000 msg use %lld\n", zclock_time () - start);
                start = zclock_time ();
            }

            zmsg_t *msg = zmsg_recv (client);
            if (!msg)
            {
                break;
            }
            //zframe_print (zmsg_last (msg), identity);
            zmsg_destroy (&msg);
        }
        if (items [1].revents & ZMQ_POLLOUT)
        {
            static int nTmp2 = 0;
            zstr_sendf (client, "request #%d", 1);
        }
 }
    zctx_destroy (&ctx);
    return NULL;
}

server code:

#include "czmq.h"

#define HEARTBEAT_LIVENESS  3       //  心跳健康度,3-5是合理的
#define HEARTBEAT_INTERVAL  1000    //  单位:毫秒

//  偏执海盗协议的消息代码
#define PPP_READY       "\001"      //  worker已就绪
#define PPP_HEARTBEAT   "\002"      //  worker心跳


//  使用以下结构表示worker队列中的一个有效的worker

typedef struct {
    zframe_t *address;          //  worker的地址
    char *identity;             //  可打印的套接字标识
    int64_t expiry;             //  过期时间
} worker_t;

//  创建新的worker
static worker_t *
s_worker_new (zframe_t *address)
{
    worker_t *self = (worker_t *) zmalloc (sizeof (worker_t));
    self->address = address;
    self->identity = zframe_strdup (address);
    self->expiry = zclock_time () + HEARTBEAT_INTERVAL * HEARTBEAT_LIVENESS;
    return self;
}

//  销毁worker结构,包括标识
static void
s_worker_destroy (worker_t **self_p)
{
    assert (self_p);
    if (*self_p) {
        worker_t *self = *self_p;
        zframe_destroy (&self->address);
        free (self->identity);
        free (self);
        *self_p = NULL;
    }
}

//  worker已就绪,将其移至列表末尾
static void
s_worker_ready (worker_t *self, zlist_t *workers)
{
    worker_t *worker = (worker_t *) zlist_first (workers);
    while (worker) {
        if (streq (self->identity, worker->identity)) {
            zlist_remove (workers, worker);
            s_worker_destroy (&worker);
            break;
        }
        worker = (worker_t *) zlist_next (workers);
    }
    zlist_append (workers, self);
}

//  返回下一个可用的worker地址
static zframe_t *
s_workers_next (zlist_t *workers)
{
    worker_t *worker = zlist_pop (workers);
    assert (worker);
    zframe_t *frame = worker->address;
    worker->address = NULL;
    s_worker_destroy (&worker);
    return frame;
}

//  寻找并销毁已过期的worker。
//  由于列表中最旧的worker排在最前,所以当找到第一个未过期的worker时就停止。
static void
s_workers_purge (zlist_t *workers)
{
    worker_t *worker = (worker_t *) zlist_first (workers);
    while (worker) {
        if (zclock_time () < worker->expiry)
            break;              //  worker未过期,停止扫描

        zlist_remove (workers, worker);
        s_worker_destroy (&worker);
        worker = (worker_t *) zlist_first (workers);
    }
}


int main (void)
{
    zctx_t *ctx = zctx_new ();
    void *frontend = zsocket_new (ctx, ZMQ_ROUTER);
    void *backend  = zsocket_new (ctx, ZMQ_ROUTER);
    zsocket_bind (frontend, "tcp://*:5555");    //  client端点
    zsocket_bind (backend,  "tcp://*:5556");    //  worker端点
    //  List of available workers
    zlist_t *workers = zlist_new ();

    //  规律地发送心跳
    uint64_t heartbeat_at = zclock_time () + HEARTBEAT_INTERVAL;

    while (1) {
        zmq_pollitem_t items [] = {
            { backend,  0, ZMQ_POLLIN, 0 },
            { frontend, 0, ZMQ_POLLIN, 0 }
        };
        //  当存在可用worker时轮询前端端点
        int rc = zmq_poll (items, zlist_size (workers)? 2: 1,
            HEARTBEAT_INTERVAL * ZMQ_POLL_MSEC);
        if (rc == -1)
            break;              //  中断

        //  处理后端worker请求
        if (items [0].revents & ZMQ_POLLIN) {
            //  使用worker地址进行LRU路由
            zmsg_t *msg = zmsg_recv (backend);
            if (!msg)
                break;          //  中断

            //  worker的任何信号均表示其仍然存活
            zframe_t *address = zmsg_unwrap (msg);
            worker_t *worker = s_worker_new (address);
            s_worker_ready (worker, workers);

            //  处理控制消息,或者将应答转发给client
            if (zmsg_size (msg) == 1) {
                zframe_t *frame = zmsg_first (msg);
                if (memcmp (zframe_data (frame), PPP_READY, 1)
                &&  memcmp (zframe_data (frame), PPP_HEARTBEAT, 1)) {
                    printf ("E: invalid message from worker");
                    zmsg_dump (msg);
                }
                zmsg_destroy (&msg);
            }
            else
                zmsg_send (&msg, frontend);
        }
        if (items [1].revents & ZMQ_POLLIN) {
            //  获取下一个client请求,交给下一个可用的worker
            zmsg_t *msg = zmsg_recv (frontend);
            if (!msg)
                break;          //  中断
            zmsg_push (msg, s_workers_next (workers));
            zmsg_send (&msg, backend);
        }

        //  发送心跳给空闲的worker
        if (zclock_time () >= heartbeat_at) {
            worker_t *worker = (worker_t *) zlist_first (workers);
            while (worker) {
                zframe_send (&worker->address, backend,
                             ZFRAME_REUSE + ZFRAME_MORE);
                zframe_t *frame = zframe_new (PPP_HEARTBEAT, 1);
                zframe_send (&frame, backend, 0);
                worker = (worker_t *) zlist_next (workers);
            }
            heartbeat_at = zclock_time () + HEARTBEAT_INTERVAL;
        }
        s_workers_purge (workers);
    }

    //  程序结束后进行清理
    while (zlist_size (workers)) {
        worker_t *worker = (worker_t *) zlist_pop (workers);
        s_worker_destroy (&worker);
    }
    zlist_destroy (&workers);
    zctx_destroy (&ctx);
    return 0;
}

worker code:

#include "czmq.h"

#define HEARTBEAT_LIVENESS  3       //  合理值:3-5
#define HEARTBEAT_INTERVAL  1000    //  单位:毫秒
#define INTERVAL_INIT       1000    //  重试间隔
#define INTERVAL_MAX       32000    //  回退算法最大值

//  偏执海盗规范的常量定义
#define PPP_READY       "\001"      //  消息:worker已就绪
#define PPP_HEARTBEAT   "\002"      //  消息:worker心跳

//  返回一个连接至偏执海盗队列装置的套接字

static void *
s_worker_socket (zctx_t *ctx) {
    void *worker = zsocket_new (ctx, ZMQ_DEALER);
    zsocket_connect (worker, "tcp://localhost:5556");

    //  告知队列worker已准备就绪
    printf ("I: worker已就绪\n");
    zframe_t *frame = zframe_new (PPP_READY, 1);
    zframe_send (&frame, worker, 0);

    return worker;
}

int main (void)
{
    zctx_t *ctx = zctx_new ();
    void *worker = s_worker_socket (ctx);

    //  如果心跳健康度为零,则表示队列装置已死亡
    size_t liveness = HEARTBEAT_LIVENESS;
    size_t interval = INTERVAL_INIT;

    //  规律地发送心跳
    uint64_t heartbeat_at = zclock_time () + HEARTBEAT_INTERVAL;

    srandom ((unsigned) time (NULL));
    int cycles = 0;
    while (1) {
        zmq_pollitem_t items [] = { { worker,  0, ZMQ_POLLIN, 0 } };
        int rc = zmq_poll (items, 1, HEARTBEAT_INTERVAL * ZMQ_POLL_MSEC);
        if (rc == -1)
            break;              //  中断

        if (items [0].revents & ZMQ_POLLIN) {
            //  获取消息
            //  - 3段消息,信封+内容,表示一个请求
            //  - 1段消息,表示心跳
            zmsg_t *msg = zmsg_recv (worker);
            if (!msg)
                break;          //  中断

            if (zmsg_size (msg) == 3) {
                //  若干词循环后模拟各种问题
                cycles++;
                if (cycles > 3 && randof (5) == 0) {
                    printf ("I: 模拟崩溃\n");
                    zmsg_destroy (&msg);
                    break;
                }
                else
                if (cycles > 3 && randof (5) == 0) {
                    printf ("I: 模拟CPU过载\n");
                    sleep (3);
                    if (zctx_interrupted)
                        break;
                }
                printf ("I: 正常应答\n");
                zmsg_send (&msg, worker);
                liveness = HEARTBEAT_LIVENESS;
                sleep (1);              //  做一些处理工作
                if (zctx_interrupted)
                    break;
            }
            else
            if (zmsg_size (msg) == 1) {
                zframe_t *frame = zmsg_first (msg);
                if (memcmp (zframe_data (frame), PPP_HEARTBEAT, 1) == 0)
                    liveness = HEARTBEAT_LIVENESS;
                else {
                    printf ("E: 非法消息\n");
                    zmsg_dump (msg);
                }
                zmsg_destroy (&msg);
            }
            else {
                printf ("E: 非法消息\n");
                zmsg_dump (msg);
            }
            interval = INTERVAL_INIT;
        }
        else
        if (--liveness == 0) {
            printf ("W: 心跳失败,无法连接队列装置\n");
            printf ("W: %zd 毫秒后进行重连...\n", interval);
            zclock_sleep (interval);

            if (interval < INTERVAL_MAX)
                interval *= 2;
            zsocket_destroy (ctx, worker);
            worker = s_worker_socket (ctx);
            liveness = HEARTBEAT_LIVENESS;
        }

        //  适时发送心跳给队列
        if (zclock_time () > heartbeat_at) {
            heartbeat_at = zclock_time () + HEARTBEAT_INTERVAL;
            printf ("I: worker心跳\n");
            zframe_t *frame = zframe_new (PPP_HEARTBEAT, 1);
            zframe_send (&frame, worker, 0);
        }
    }
    zctx_destroy (&ctx);
    return 0;
}

Print all the unique elements of an array

I am trying to print all the unique elements of a given array using a binary search tree.

What I am doing:

  1. Input all the numbers in an array.
  2. Search for each element of the array one by one in the bst,
    • if (an element is not found in the bst)
      • put it there and print it
    • else
      • go to the next element
#include<stdlib.h>
#include<stdio.h>

struct node
{   
    int data;
    struct node* left;
    struct node* right;
} *root = NULL;

void insert(struct node *n, int value)
{
    if (n == NULL)
    {
        n = (struct node*)malloc(sizeof(struct node));
        n->data = value;
        n->left = NULL;
        n->right = NULL;
        printf("%d ", value);
        return;
    }

    if ((n->data) == value)
        return;
    if ((n->data) > value)
        insert(n->left, value);
    else
        insert(n->right, value);
}   

int main()
{
    int a[100], i, n;
    printf("Enter the number of elements : ");
    scanf("%d",&n);
    for (i = 0; i < n; i++)
        scanf("%d",&a[i]);
    printf("After removal of duplicates, the new list is : \n");
    for (i = 0; i < n; i++)
        insert(root, a[i]);
    printf("\n");
    return 0;
}       

Does C supports compiler directive that prints a message without issuing warning or error? [duplicate]

This question already has an answer here:

The purpose was to print a message while compiling that acts as a reminder and it should not cause warning or error.

For e.g

void stub()
{
 // print a message say "TODO: Implement this before committing the changes"
}

Used #warning without strict option but it was still giving warning message.

SDL_Mixer error "Mixer not built with ... support"

I am trying to play music in the background of a game I'm working on. I'm using SDL2 and SDL-mixer for the first time. I compiled them myself and put the files at the root of my program folder (for portability purposes). Now when I run the game, no sound is playing and Mix_GetError() returns this error:

"Mixer not built with MP3 support"

I'm trying to play a MP3 file, but I get the same error when I try to initialize with OGG and other formats.

Here's the function, if it's at all relevant.

int     play_sound(void)
{
    int         mp3;
    Mix_Music   *music;

    mp3 = MIX_INIT_MP3;
    music = NULL;
    if (mp3 != Mix_Init(mp3))
        return (put_error(Mix_GetError()));
    if (Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096) == -1)
        return (-1);
    music = Mix_LoadMUS("data/music.mp3");
    Mix_PlayMusic(music, -1);
    return (0);
}

I haven't found much on that particular issue, but I think the problem comes from me compiling SDL2 and SDL-mixer from sources. I must've forgot something, but I don't really know... I'm on OSX by the way (and not really used to it yet).

Thanks everyone for the help!

edit/ I have not tried with a WAV file.

Delete a file instead of marking it for deletion

I am writing a service for Windows (from XP to 8.1). I need to recursively delete a folder and I use DeleteFile and RemoveDirectory for that. I don't want to use SHFileOperation because it has the MAX_PATH limit.

The problem is that sometimes, RemoveDirectory fails with ERROR_DIR_NOT_EMPTY, even if the directory is empty. I found out that this is because DeleteFile works asynchronously, it only "marks" a file for deletion. Therefore, adding a small delay (Sleep) before calling RemoveDirectory fixes the issue. But I am looking for a cleaner method.

So, is there a way to ensure that the marked files are well and truly deleted?

I already tried to call FlushFileBuffers directly on the directory, without success.

Changing address contained by structure and its members using function (ANSI C)

I want to do a constructor object-oriented-like function in C, but the address of my structure and its members are not being changed after I malloc() them. I saw this answer Changing address contained by pointer using function and I got an idea of what my problem is, but still can't solve it. Below is my code that is doing the constructor:

udp.h

typedef struct{
    int socket;
    char header[3];
    float *send_value;
    char *message_buffer;
}message;

void build_message(message **msg, int socket, char *header,float *send_value);

main.c

message *message_Ta = NULL;
build_message(&message_Ta, socket_cliente, "sta", &Ta);
sprintf(message_Ta->message_buffer, "%s0.0", message_Ta->header);

udp.c

void build_message(message **msg, int socket, char header[], float *send_value){
    *msg = malloc(sizeof(message)+sizeof(int)+sizeof(float *) + HEADER_SIZE + BUF_SIZE);
    msg->socket = socket;
    strcpy(msg->header, header);
    msg->send_value = send_value; 
    msg->message_buffer = NULL; 
    msg->message_buffer = malloc(BUF_SIZE);
}

Btw, I am using threads in these code, would this code be thread-safe even without mutexes? thx in advance

Check if bit has toggled in C

I am working on bitwise manipulation (in C) and I wanted to know how to check if a bit has toggled between a previous value and the new value.

Example :
    oldValue = 0x0FF //0000 1111 1111 in binary
    newValue = 0x100 //0001 0000 0000 in binary

In this example I want to check if the bit8 (9th bit) has toggled from 0 to 1.

I know that if I want to know if a bit is set, is can use :

value & (1 << 8)

So, is this correct ? :

if( (oldValue & (1 << 8)) == (newValue & (1 << 8)) ) //return 0 if toggled

utopian tree using c

i am making a utopian tree in which if the tree height is 1 at first and every first year it doubles and second it increses by +1; so please suggest me right ans with cases for example There are 3 test cases.

In the first case (N=0), the initial height (1) of the tree remains unchanged.

In the second case (when N = 1, i.e. after the 1st cycle), the tree doubles its height as it's planted at the onset of spring.

In the third case (N=4), the tree first doubles its height (2), then grows a meter (3), then doubles again (6), before growing another meter; at the end of the 4th cycle, its height is 7 meters. and the sample code is

#include<stdio.h>

int main()
{
    int years,m,n,p,q,j;
    int height=1;
    int cases;
    int array[m];

    scanf("%d",&cases);

    for(m=0;m<cases;m++) 
    { 

     scanf("%d",&years[m]);
    }  

    j=0;

    for(n=0;n<=years[j];n++)
    {

       j<cases;

       j++;
       p=n;
       q=p%2;
       if(q==0)
          height=height*2;
       else
          height = height+1;
    }

  printf("%d",height);

 return 0;
}

I tried every possible way to do but I did not get the right answer.

How do i measure the running time of my program in C?

I have written this program in C that prints all the prime numbers til the one read at the top of the program. This is the program:

int i,j;
bool *p;
int g;
printf("inserisca la grandezza della tabella: ");
scanf("%i",&g);
wait(1);
p=(bool *)malloc(g*sizeof(bool));
    for(i=0;i<g+1;i++){
        p[i]=true;
    }
i=2;
while(i<=(g-2)){
    while(!p[i]){
        i++;
    }
    j=i+i;
    while(j<=(g-1)){
        p[j]=false;
        j=j+i;
    }
    i++;
}
j=0;
for(i=1;i<g;i++){
    if(p[i]!=false){
        printf("\t%i\n",i);
        j++;
    }
}
printf("sono stati trovati %i numeri primi\n",j);
free(p);

My problem is i want to know how much milliseconds or nanoseconds it takes the program to allocate the memory and do the calculations? Have i to include some libraries like time.h? Please don't mind the lenguage i'm an italian student.

Why printf is not printing garbage value?

#include<stdio.h>
void foo(){
int i;
printf("%d\n",i);  //should print garbage value
}
void main(){
foo();
}

foo should print garbage value of i. But instead it is printing zero. Why is that? I am using gcc version 4.9.2.

Warning: Suspicious pointer-to-pointer conversion (area too small) with lint

long keyIntValue;
uint8_t *value; 

*(long *)value = keyIntValue;

I get Suspicious pointer-to-pointer conversion (area too small) while linting. Help me to understand why I get it and how to get rid of it?

How to scanf to just one dimension of a multidimensional array in C?

Suppose I have some C code like this, which declares a small multidimensional array:

#include <stdio.h>
#include <conio.h>

int main(void)
{
    int mat[5][2] = {
        {0, 0},
        {0, 0},
        {0, 0},
        {0, 0},
        {0, 0}
    }

    do scanf("%i", &mat[][]);
    while (getchar() != '\n');  

    return 0;
}

and I want to change do scanf("%i", &mat[][]);, and possibly the line below it, to something which will allow me to read user-supplied integers into only the 2nd column of this 5-by-2 multidimensional array.

Iam trying to find the simplest possible solution, without concern for software security and hopefully without unnecessarily calling libaries.

Measurement of TLB effects on a Cortex-A9

after reading the following paper http://ift.tt/1clYByk ("What every programmer should know about memory") I wanted to try one of the author's test, that is, measuring the effects of TLB on the final execution time.

I am working on a Samsung Galaxy S3 that embeds a Cortex-A9.

According to the documentation:

  • we have two micro TLBs for instruction and data cache in L1 (http://ift.tt/1LR3hrp)

  • The main TLB is located in L2 (http://ift.tt/1LR3hrp)

  • Data micro TLB has 32 entries (instruction micro TLB has either 32 or 64 entries)

  • L1' size == 32 Kbytes
  • L1 cache line == 32 bytes
  • L2' size == 1MB

I wrote a small program that allocates an array of structs with N entries. Each entry's size is == 32 bytes so it fits in a cache line. I perform several read access and I measure the execution time.

typedef struct {
     int elmt; // sizeof(int) == 4 bytes
     char padding[28]; // 4 + 28 = 32B == cache line size
}entry;


volatile entry ** entries = NULL;

//Allocate memory and init to 0
entries = calloc(NB_ENTRIES, sizeof(entry *));
if(entries == NULL) perror("calloc failed"); exit(1);

for(i = 0; i < NB_ENTRIES; i++)
{
      entries[i] = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
      if(entries[i] == MAP_FAILED) perror("mmap failed"); exit(1);
}


InitWithRandomValues(&entries);
entries[LAST_ELEMENT]->elmt = -1

gettimeofday(&tStart, NULL);
for(i = 0; i < NB_LOOPS; i++)
{
     j = 0;
     while(j != -1)
     {
          j = entries[j]->elmt
     }
}
gettimeofday(&tEnd, NULL);

time = (tEnd.tv_sec - tStart.tv_sec);
time *= 1000000;
time += tEnd.tv_usec - tStart.tv_usec;
time *= 100000
time /= (NB_ENTRIES * NBLOOPS);

fprintf(stdout, "%d %3lld.%02lld\n", NB_ENTRIES, time / 100, time % 100);

I have an outter loop that makes NB_ENTRIES vary from 4 to 1024.

As one can see in the figure below, while NB_ENTRIES == 256 entries, executin time is longer.

When NB_ENTRIES == 404 I get an "out of memory" (why? micro TLBs exceeded? main TLBs exceeded? Page Tables exceeded? virtual memory for the process exceeded?)

Can someone explain me please what is really going on from 4 to 256 entries, then from 257 to 404 entries?

Effects of TLB on execution time

Eclipse C lua integration

I'm trying to get lua to integrate into my eclipse C environment. This should be a straightforward process of just including a few files, however I am getting an 'undefined reference' to every lua function called. Code: (keep in mind this is directly copied from http://ift.tt/1z3Ditl)

/*
 * test.c
 * Example of a C program that interfaces with Lua.
 * Based on Lua 5.0 code by Pedro Martelletto in November, 2003.
 * Updated to Lua 5.1. David Manura, January 2007.
 */

#include "C:/Users/Dylan/workspace/C in Lua/lua/lua.h"
#include "C:/Users/Dylan/workspace/C in Lua/lua/lauxlib.h"
#include <stdlib.h>
#include <stdio.h>


int
main(void)
{
    int status, result, i;
    double sum;
    lua_State *L;

    /*
     * All Lua contexts are held in this structure. We work with it almost
     * all the time.
     */
    L = luaL_newstate();

    luaL_openlibs(L); /* Load Lua libraries */

    /* Load the file containing the script we are going to run */
    status = luaL_loadfile(L, "script.lua");
    if (status) {
        /* If something went wrong, error message is at the top of */
        /* the stack */
        fprintf(stderr, "Couldn't load file: %s\n", lua_tostring(L, -1));
        exit(1);
    }

    /*
     * Ok, now here we go: We pass data to the lua script on the stack.
     * That is, we first have to prepare Lua's virtual stack the way we
     * want the script to receive it, then ask Lua to run it.
     */
    lua_newtable(L);    /* We will pass a table */

    /*
     * To put values into the table, we first push the index, then the
     * value, and then call lua_rawset() with the index of the table in the
     * stack. Let's see why it's -3: In Lua, the value -1 always refers to
     * the top of the stack. When you create the table with lua_newtable(),
     * the table gets pushed into the top of the stack. When you push the
     * index and then the cell value, the stack looks like:
     *
     * <- [stack bottom] -- table, index, value [top]
     *
     * So the -1 will refer to the cell value, thus -3 is used to refer to
     * the table itself. Note that lua_rawset() pops the two last elements
     * of the stack, so that after it has been called, the table is at the
     * top of the stack.
     */
    for (i = 1; i <= 5; i++) {
        lua_pushnumber(L, i);   /* Push the table index */
        lua_pushnumber(L, i*2); /* Push the cell value */
        lua_rawset(L, -3);      /* Stores the pair in the table */
    }

    /* By what name is the script going to reference our table? */
    lua_setglobal(L, "foo");

    /* Ask Lua to run our little script */
    result = lua_pcall(L, 0, LUA_MULTRET, 0);
    if (result) {
        fprintf(stderr, "Failed to run script: %s\n", lua_tostring(L, -1));
        exit(1);
    }

    /* Get the returned value at the top of the stack (index -1) */
    sum = lua_tonumber(L, -1);

    printf("Script returned: %.0f\n", sum);

    lua_pop(L, 1);  /* Take the returned value out of the stack */
    lua_close(L);   /* Cya, Lua */

    return 0;
}

The paths for the headers are correct, and I had to add the path to lua.h, after that Eclipse no longer complained about missing files, however it marks all lua functions and says this in the debugger after building: Description Resource Path Location Type

Description Resource    Path    Location    Type
undefined reference to `lua_close'  hello-world.c   /C in Lua   line 82 C/C++ Problem
undefined reference to `lua_createtable'    hello-world.c   /C in Lua   line 43 C/C++ Problem
undefined reference to `lua_pcall'  hello-world.c   /C in Lua   line 70 C/C++ Problem
undefined reference to `lua_pushnumber' hello-world.c   /C in Lua   line 61 C/C++ Problem
undefined reference to `lua_pushnumber' hello-world.c   /C in Lua   line 62 C/C++ Problem
undefined reference to `lua_rawset' hello-world.c   /C in Lua   line 63 C/C++ Problem
undefined reference to `lua_setfield'   hello-world.c   /C in Lua   line 67 C/C++ Problem
undefined reference to `lua_settop' hello-world.c   /C in Lua   line 81 C/C++ Problem
undefined reference to `lua_tolstring'  hello-world.c   /C in Lua   line 34 C/C++ Problem
undefined reference to `lua_tolstring'  hello-world.c   /C in Lua   line 72 C/C++ Problem
undefined reference to `lua_tonumber'   hello-world.c   /C in Lua   line 77 C/C++ Problem
undefined reference to `luaL_loadfile'  hello-world.c   /C in Lua   line 30 C/C++ Problem
undefined reference to `luaL_newstate'  hello-world.c   /C in Lua   line 25 C/C++ Problem
undefined reference to `luaL_openlibs'  hello-world.c   /C in Lua   line 27 C/C++ Problem

(as seen the program source is called 'helloworld.c') Please help.

Printing an array of characters in C with "while"

So here is the working version:

#include <stdio.h>

int main(int argc, char const *argv[]) {
    char myText[] = "hello world\n";
    int counter = 0;
    while(myText[counter]) {
        printf("%c", myText[counter]);
        counter++;
    }
}

and in action:

Korays-MacBook-Pro:~ koraytugay$ gcc koray.c
Korays-MacBook-Pro:~ koraytugay$ ./a.out 
hello world

My question is, why is this code even working? When (or how) does

while(myText[counter])

evaluate to false?

These 2 work as well:

while(myText[counter] != '\0')
while(myText[counter] != 0)

This one prints garbage in the console:

while(myText[counter] !=  EOF)

and this does not even compile:

while(myText[counter] != NULL)

I can see why the '\0' works, as C puts this character at the end of my array in compile time. But why does not NULL work? How is 0 == '\0'?

performance cache memories with buffer

like a class exercise I need to work with cache memories.

This is the statement:

  Your program should measure average bandwidth of the byte access during
  many rounds of execution of the following two subroutines:

  subroutine A: increment all bytes of a memory buffer containing 2*s1
  bytes in the order of increasing memory addresses;

  subroutine B: increment each b1-th byte of a memory buffer containing 2*s1 
  bytes in the order of increasing memory addresses;

  Subroutines B employ the memory buffer which is exactly twice as large as
  the capacity of the analyzed cache L1. By using such memory buffers we
  ensure that the buffer is smaller than the capacity of the memory at the
  next level of the memory hierarchy (if we are testing L1, the buffer is
  smaller than L2).

  Each of these two subroutines has to be invoked many times in the loop.
  We see that the subroutine A relatively seldom generates L1 cache misses    
  (once in b1 accesses). Subroutine B generates a L1 cache miss in each
   memory access, but a majority of these accesses shall fall inside L2

  For each subroutine, your program should determine average time of a byte
  access, as well as the achieved bandwidth in MB/s. Based on the obtained
  data, estimate the ratios of the latencies corresponding to neighbouring
  levels of the memory hierarchy (t(L2)/t(L1), t(RAM)/t(L2)).

I have done the subroutine A, but subroutine B, I do not really understand how to increment that.

This is subroutine A. I think that I did it correctly (just increment all buffer and I checked for cache misses with perf like this ¨perf stat -e cache-misses ./lab¨, but it put me it is not supported ):

My cache is capacity of L1 cache 32kb (s1). Line witdh 64 bytes.

char buffer1[2*32768];

I fill out this buffer with aleatory.

void subroutine_A(char *buffer1)
{
   buffer1++; 
}

It is the first time that I have to work with this and I am quite lost, I checked on internet, but I did not find anything really helpfull for me and I am trying to do this since long time ago, so, with any help I would be really gratefull :)

Thanks.

Is it possible to peek at the next rand value

Assuming the generator has been seeded, it is possible to peek at the next random value without changing it?

i.e. given:

#include <stdlib.h>

int r;
r = rand(); // say this is 99
r = rand(); // say this is 80

Is this possible

#include <stdlib.h>

int r;
r = peekAtRand(); // this will give 99
r = rand(); // but this still gives 99

r = peekAtRand(); // this will give 80
r = rand(); // but this still gives 80

Furthermore, can this be extended to peeking at the next n numbers?

recursive function that tells if a Tree is a Binary Search Tree ( BST ) (Modified code)

I was working on the exercises here : "http://ift.tt/1LMovHG"
I wrote a function that decides if a Tree is a BST(return 1) or not(return 0) but I'm not sure if my code is totally good, I tested it for a BST and a non-BST Tree and it seems to work correctly. I want to know the opinion of the community : Updated Code :

consider the Tree ( not a BST ) :

     5  
    / \ 
   2   7 
  / \ 
 1   6

my Idea is to compare 2 with 5 if it's good, then 1 with 5, and if it's good then 6 with 5 if it's good then 1 with 2 if it's good then 6 with 2 if it's good then 5 with 7 ; if it's good isBST() returns 1. this code is supposed to do it recursively.

the node structure :

struct node {
    int data;
    struct node* left;
    struct node* right;
};

the code :

int lisgood(struct node* n1,struct node* n2)
{
    if(n2 == NULL)
        return 1;
    else{
    int r = lisgood(n1,n2->left)*lisgood(n1,n2->right);
        if(r){
            if(n1->data >= n2->data)
            {
                return r;
            }
            else return 0;
        }
        else return r;
    }
}
int risgood(struct node* n1,struct node* n2)
{
    if(n2 == NULL)
        return 1;
    else{
        int r = risgood(n1,n2->right)*risgood(n1,n2->left);
        if(r){
            if(n1->data < n2->data)
            {
                return r;
            }
            else return 0;
        }
        else return r;
    }
}

int isBST(struct node* node)
{
    if(node == NULL)
        return 1;
    else{
        if(lisgood(node,node->left)&&risgood(node,node->right)){
            return (isBST(node->left)&&isBST(node->right));
        }
        else return 0;
    }
}

Diagnosing issues with the system(command) call?

I have an application that at some point calls

system("/usr/sbin/iptables -t nat F")

to flush the ip tables. Since the application is multi threaded and developed by multiple developers, at some point the iptables stopped being set. It turned out that I'm not able to lunch external processes (have also tried system("/bin/ls") without success). The commands can be run from the shell with no issues.

I get the return value -1 regardless of the command called. Is there a way to get some more information on why this is failing?

How to count frequency of word in c

Assume we have an array :

you are alien and they are human

So, how to count the kind of string?

Output :

you = 1 word

modified bubble sort not showing the passes

My code is not showing the first pass when I entered the value 1,2,3,4,5 because of the

  • count condition which i have used. But i want my code to show at least 1 pass if it is in sorted order also.
  • stop the process if u find that the list is sorted in any intermediate point.

Here is my code:

#include<stdio.h>

int main()
{

    int s,i,j,temp,a[20],count=0,x,n=0;

    printf("Enter the number of elements :\n");
    scanf("%d",&s);

    for(i=0;i<s;i++)
    {
        printf("Enter element %d\n",i+1);
        scanf("%d",&a[i]);
    }
    printf("Unsorted list is :\n");
    for(i=0;i<s;i++)
    {
        printf("%d ",a[i]);
    }

    for(i=0;i<(s-1);i++)
    {
        count=0;
        n++;
        for(j=0;j<(s-i)-1;j++)
        {
            if(a[j]>a[j+1])
            {
                temp=a[j];
                a[j]=a[j+1];
                a[j+1]=temp;
                count++;
            }
        }

        if(count<=0)
        {
            break;
        }
        else
        {
            printf("\nAfter Pass %d elements are :",n);
            for(x=0;x<s;x++)
            {
                printf("%d ",a[x]);
            }
        }
    }

    printf("\nSorted list is :\n");
    for(i=0;i<s;i++)
        printf("%d ",a[i]);
    return 0;
}

Help me out guys,Your suggestion and idea would be very thankful to me.

Com port write read methodology

I'm communicating with a Wince 6.0 embedded device and read/write some data by c/c++ code. Now I'm using below code snippets for read/write to com port.

void ConvertIntToByte(int iValue, BYTE* ucRawBuffer, int iOffset)
{
  ucRawBuffer[iOffset]   = ((iValue >> 24) & 0xFF);
  ucRawBuffer[iOffset+1] = ((iValue >> 16) & 0xFF);
  ucRawBuffer[iOffset+2] = ((iValue >> 8) & 0xFF);
  ucRawBuffer[iOffset+3] = (iValue & 0xFF);
}

ReadWriteDataThread()
{
    BYTE ucInitMsg[32] = {0};
    ucInitMsg[0] = 0x0A;
    ConvertIntToByte(iUTCTime, ucInitMsg, 1);
    ucInitMsg[21] = 0x02;
    ucInitMsg[22] = 0x3E;
    ucInitMsg[31] = 0xCA;
    m_objComm.WriteCommPort(ucInitMsg, 32);  //Its a standard comm port write function which used WriteFile windows API
}

Now, my concern is am I writing Bytes to com port in correct manner? Am I doing correct in bit shifting? I found the code for int to byte conversion on web and I'm not very much strong in bit/byte manipulation.

How Can I receive messages from more than one named pipes?

I have to use a fifo in my code.

I use sock to accept new client. For each client I create new thread to send and receive message to him.

In the function of the thread I use fifo to send and receive messages also to another process and here is my code:

 int s_to_c=open(myfifo1,O_WRONLY);
 int c_to_s=open(myfifo2,O_RDONLY);

 char echoBuffer[RCVBUFSIZE];           
 int recvMsgSize; 

 for(;;)
 {   
     bzero(echoBuffer,RCVBUFSIZE);              
     read(c_to_s, echoBuffer, RCVBUFSIZE);  
     write(sock, echoBuffer, strlen(echoBuffer));
     bzero(echoBuffer,RCVBUFSIZE);

     read(sock, echoBuffer, RCVBUFSIZE);
     write(s_to_c,echoBuffer,strlen(echoBuffer));
}

close(c_to_s);
close(s_to_c);
close(sock);

And on the other side (The other process) my code:

int s_to_c=open(myfifo1,O_RDONLY);
int c_to_s=open(myfifo2,O_WRONLY);

char echoBuffer[RCVBUFSIZE];     
int recvMsgSize;
for(;;)
{
    bzero(echoBuffer,RCVBUFSIZE);
    fgets(echoBuffer,RCVBUFSIZE,stdin);
    echoBuffer[strlen(echoBuffer)-1]='\0';

    write(c_to_s, echoBuffer, strlen(echoBuffer));

    bzero(echoBuffer,RCVBUFSIZE);

    read(s_to_c, echoBuffer, RCVBUFSIZE);
    printf("%s\n", echoBuffer);
}

My problem is in this process : s_to_c and c_to_s take always the value(3,4).

So the first client connect correctly sending and receiving his message.

But when the second connect the first client become disable.And the messages of the second client sends and receives to and from the two processes.

Can I have some help please.Should I have to use tags for example??

Use of MPI_COMM_SELF

I've discovered an MPI communicator called MPI_COMM_SELF. The problem is, I don't know, when is it useful. It appears to me, that just every process "thinks" about itself as root.

Could you explain me how does MPI_COMM_SELF exactly work and in which situations is it useful?

I've found this slide-show, but the communicator is only briefly mentioned there.


I've tried this "Hello, world" example and all processes returned 0 as their PID.

#include <mpi.h>
#include <stdio.h>

int main() {
    MPI_Init(NULL, NULL);

    int world_rank;
    MPI_Comm_rank(MPI_COMM_SELF, &world_rank);

    printf("Hello, my PID is %d!\n",
            world_rank);

    MPI_Finalize();
    return 0;
}

mercredi 6 mai 2015

Why using static classes to share global data is not a good practice? [on hold]

I have heared that sharing data using static class properties is not a good practice. Although I haven't seen any one using this approach but I can't find out what are the drawbacks for such appraoch! To be more clear, Let's consider a WPF application composed of many UserControls that share data and parameters in a certain flow; using a static reference will make it easy to access/share these data, but no one seems to like this approach, Why?

I am expecting an anti-pattern related answer, I am just not sure what it is.

How to copy content from Label and TextBlock in WPF?

I want to copy content from label and textbox in WPF. How will we copy content from Label and TextBlock in WPF?

How do I 'watch' list box selection change?

In WPF VB.NET 4.0, I have a list box that is populated with a data binding from XML. How can I set a live watch event to the listbox so that the selected item, based on a certain criteria (field is true or false), a button on the form has it's content changed to read something else?

i.e., user selects an item with XML element 'status' is set to 'current', then button would read, Finished. If user selects an item with XML element 'status' is set to 'finished', then button would read, Unfinished.

Hide NewItemPlaceHolder in ListBox WPF

WPF

I have a problem with DataGrid and ListBox. Users can add new rows to datagrid, but an empty row is visible in listbox.

I found info about NewItemPlaceHolder, but I don't know how to hide it in listbox.

Please, help me! :D

XAML:

ListBox AlternationCount="2" ItemContainerStyle="{StaticResource alternatingWithTriggers}" x:Name="ViewListBox" Background="AliceBlue" ItemsSource="{Binding Converter={StaticResource IgnoreNewItemPlaceholderConverter}}"

CS:

    public static readonly IgnoreNewItemPlaceholderConverter Instance = new IgnoreNewItemPlaceholderConverter();

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
            if (value != null && value.ToString() == "{NewItemPlaceholder}")
            {

                return DependencyProperty.UnsetValue;
            }
            MessageBox.Show(value.ToString());
            return value;


    }

How to set selectedValue to Controls.Combobox in c#?

I have a combobox and I see that I am not able to set SelectedValue like this:

cmbA.SelectedValue = "asd"

So I tried to do this

cmbA.SelectedIndex = cmbA.FindString("asd");

Based on How to set selected value from Combobox?

I realised that my combobox is a System.Windows.Controls.ComboBox and not a System.Windows.Forms.ComboBox.

That means that FindString() is not available.

Based on User Control vs. Windows Form I get that forms are the container for controls, but I dont get why the Controls.ComboBox does not implement FindString().

Do I have to write my own code to do what FindString() does for Forms.ComboBox?

How to embed VBA into your .net application

I have small excel-like app in WPF. I would like to extend it with a possibility of embedding a VBA editor into it and exposing a small api to it. Pretty much the same way as the excel.

How to embed IronPython in a .NET application

Similar as this, but I would rather use VBA and not ironpython if possible.

C# WPF, Datepicker validation

I'm trying to validate date in XAML using validation rules.

<StackPanel Grid.Column="0" Grid.Row="1" Orientation="Horizontal">
    <DatePicker Height="25"  x:Name="DatePickerDate">
        <DatePicker.SelectedDate>
            <Binding Path="ViewModel.Date" NotifyOnValidationError="True">
                <Binding.ValidationRules>
                    <validationRules:DatePickerValidationRule/>
                </Binding.ValidationRules>
            </Binding>
        </DatePicker.SelectedDate>
    </DatePicker>
</StackPanel>

And Validation rule

public class DatePickerValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        var date = (DateTime) value;

        return date.Date.CompareTo(DateTime.Now) < 0
            ? new ValidationResult(false, "the date can not be before today")
            : new ValidationResult(true, null);
    }
}

But when I put breakpoint into validation rule, it never goes there even if I change the Date.

Since I am new to WPF, it would be appreciable if any suggestions or guidance are available here.

Thanks.

Xaml animation for button with click if completed

Intention: MouseEnter-triggered animation for app-wide each button.

Details:

  • Animation should not happen if a button is pushed by spacebar.
  • If animation is finished, button should be clicked.
  • If button is clicked or pushed by user while animation is running, animation should stop at once (disappear).
  • Xaml-only code, if possible, otherwise C#

Basic code for App.xaml:

<Style TargetType="{x:Type Button}">
    <Style.Triggers>
        <EventTrigger RoutedEvent="MouseEnter">
            <EventTrigger.Actions>
                <BeginStoryboard Name="buttonStoryboard">
                    <Storyboard>
                        <DoubleAnimation From="0" To="1" Duration="0:0:2.5" Storyboard.TargetProperty="(Opacity)" />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger.Actions>
        </EventTrigger>
    </Style.Triggers>
</Style>

Any help would be appreciated.

Access parent window control WPF

I have two windows:

ListItemWindow

(parent) that contain ocItems as ObservableCollection

DetailItemWindow

I called DetailItemWindow from ListItemWindow (DetailItemWindow.ShowDialog())

From DetailItemWindow How can I access to ocItems ?

Converting double to float C# WPF

I need to display information in a datagrid from my tblSysproStock table. The table has columns with float values in them and in my application I need to convert the double value to a float value

My coding where I want to fill my datagrid:

private void FillSysproDataGrid()
{
    using (DataClassesDataContext DC = new DataClassesDataContext())
    {
        dgSysproStock.ItemsSource = DC.tblSysproStocks.Where<tblSysproStock>(c => c.StockID != null)
            .Select<tblSysproStock, SSData>(m => new SSData()
            {
                SID = m.StockID,
                SCode = m.StockCode,
                SDescription = m.StockDescription,
                SConvFactAltUom = (float)m.ConvFactAltUom,
                SConvMulDiv = m.ConvMulDiv,
                SConvFactOthUom = (float)m.ConvFactOthUom,
                SMulDiv = m.MulDiv,
                SMass = (float)m.Mass,
                SUpdatedSupplier = m.UpdatedSupplier,
                SCycleCount = (float)m.CycleCount,
                SProductClass = (float)m.ProductClass,
                SUnitCost = (float)m.UnitCost,
                SSegal = m.Segal,
                SWareHouse = m.Warehouse,
                SMinimumStock = (float)m.MinimumStock,
                SMaximumStock = (float)m.MaximumStock,
                SStockForNow = (float)m.StockForNow,
                SStockCount = m.StockCount,
                SValue = (float)m.Value,
            });
    }
}

I am equaling my values from my table to my SSData class:

public struct SSData
{
    public string _ss;

    public int SID { get; set; }
    public string SCode { get; set; }
    public string SDescription { get; set; }
    public float SConvFactAltUom { get; set; }
    public string SConvMulDiv { get; set; }
    public float SConvFactOthUom { get; set; }
    public string SMulDiv { get; set; }
    public float SMass { get; set; }
    public string SUpdatedSupplier { get; set; }
    public float SCycleCount { get; set; }
    public float SProductClass { get; set; }
    public float SUnitCost { get; set; }
    public string SSegal { get; set; }
    public string SWareHouse { get; set; }
    public float SMinimumStock { get; set; }
    public float SMaximumStock { get; set; }
    public float SStockForNow { get; set; }
    public string SStockCount { get; set; }
    public float SValue { get; set; }
}

Now the error that I am getting is -

The null value cannot be assigned to a member with type System.Single which is a non-nullable value type. When I run my application.

I think that it's the conversion that is the problem? Anyone with any advice or solutions would be great! Thank you.

wpf copy and replace file doesn't update image in window

I have window to manage the books table, in this window there is a image which has its source property filled with the image name. For that I have this method.

protected void bindImage()
{
    string folderPath = System.IO.Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + "\\bookImages\\";
    folderPath += tbLivrosRow.Imagem.ToString();
    BitmapImage bitMapImage = new BitmapImage();
    bitMapImage.BeginInit();
    bitMapImage.UriSource = new Uri(folderPath);
    bitMapImage.CacheOption = BitmapCacheOption.OnLoad;
    imgBookCover.Source = bitMapImage;
    bitMapImage.EndInit();
}

To change the book cover...

private void changeCover(object sender, RoutedEventArgs e)
{
    OpenFileDialog CxDialog = new OpenFileDialog();
    string folderPath = System.IO.Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + "\\bookImages\\";
    CxDialog.Title = "Seleccione a capa pretendida";
    CxDialog.Filter = "JPEG (*.jpg)|*.jpg|PNG (*.png)|*.png";
    CxDialog.FilterIndex = 1; // com o valor 1 aparece na caixa de diálogo o primeiro filtro de pesquisa, *.JPG
    CxDialog.CheckFileExists = true;
    bool? myResult;
    myResult = CxDialog.ShowDialog();
    if (myResult != null && myResult == true)
    {
        string filePath = folderPath + tbLivrosRow.Imagem.ToString().Trim();
        System.IO.File.Copy(CxDialog.FileName, filePath, true);
        imgBookCover.Source = null;
        Bind();
    }
}

The Bind() fills some listViews, textboxes, etc. and calls the bindImage().

The image is successfully copied to the destination folder, replaces the existing one, but the image never gets updated in the window.xaml. The image only updates after I exit this window.

I have tried to set the image source property to null but it does not get it done.

How to prevent NullReferenceException from being thrown in the first place

I'm having some trouble dealing with the "NullReferenceException" that keeps getting thrown.

Exception

You see I'm working with an ICollectionView.

This ICollectionView has a filter I use to search a DataGrid.

In this same datagrid, there is a SelectedItem attribute that is bound to a property called SelectedUser also within the same ViewModel.

<DataGrid x:Name="principalDataGrid"
          ItemsSource="{Binding PrincipalView, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
          SelectedItem="{Binding SelectedUser, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">

The problem is, when ever I search for something that isn't there, the above exception gets thrown as seen in the image.

This is my property

    public string Member
    {
        get
        {
            // The exception Highlights this when thrown.
            return SelectedUser.member;
        }
        set 
        {
            SelectedUser.member = value;
            OnPropertyChanged("Member");
        }
    }

To a degree I can understand what's happening. When the filter is invoked, it narrows down the number of items the Datagrid displays according to what's been typed in as the search parameter. How ever when what you type in that TextBox is not found, the DataGrid will be empty and the SelectedItem becomes null.

The thing is, instead of catching the exception, I need to ensure it never happens in the first place. i.e (The same property as above with a modification):

    public string Member
    {
        get
        {
            if (SelectedUser != null)
                return SelectedUser.member;
            else
                // What would I put here to avoid the error?
                return .................;
        }
        set 
        {
            if (SelectedUser != null)
                SelectedUser.member = value;
            OnPropertyChanged("Member");
        }
    }

I just intend for the datagrid to come up empty when what's being searched for / filtered is not there in it with no need for an error message.

How to move focus with in columns inside one grid cell

I have grid designed something like below:

This is xaml used for a grid:- I am using devexpress gridcontrol in my application.

<dxg:GridControl ItemsSource="{Binding MyAddresses}">
        <dxg:GridControl.View>
            <dxg:TableView NavigationStyle="Cell"></dxg:TableView>
        </dxg:GridControl.View>
        <dxg:GridControl.Columns>
            <dxg:GridColumn Name="MyAddress" Header="Address" MinWidth="725">
                <dxg:GridColumn.CellTemplate>
                    <DataTemplate>
                        <Grid DataContext="{Binding RowData.Row}" HorizontalAlignment="Stretch" VerticalAlignment="Center" Margin="5">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto"></RowDefinition>
                                <RowDefinition Height="5"></RowDefinition>
                                <RowDefinition Height="Auto"></RowDefinition>
                                <RowDefinition Height="5"></RowDefinition>
                                <RowDefinition Height="Auto"></RowDefinition>
                                <RowDefinition Height="5"></RowDefinition>
                                <RowDefinition Height="Auto"></RowDefinition>
                                <RowDefinition Height="5"></RowDefinition>
                                <RowDefinition Height="Auto"></RowDefinition>
                                <RowDefinition Height="5"></RowDefinition>
                                <RowDefinition Height="Auto"></RowDefinition>
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"></ColumnDefinition>
                                <ColumnDefinition Width="5"></ColumnDefinition>
                                <ColumnDefinition MinWidth="250"></ColumnDefinition>
                                <ColumnDefinition Width="25"></ColumnDefinition>
                                <ColumnDefinition Width="Auto"></ColumnDefinition>
                                <ColumnDefinition Width="5"></ColumnDefinition>
                                <ColumnDefinition MinWidth="250"></ColumnDefinition>
                            </Grid.ColumnDefinitions>

                            <TextBlock Grid.Row="0" Grid.RowSpan="3" Grid.Column="0" Text="Address"/>
                            <dxe:TextEdit Grid.Row="0" TextWrapping="Wrap" AcceptsReturn="True" VerticalContentAlignment="Top" Grid.RowSpan="3" Grid.Column="2" MaxLength="2000" VerticalAlignment="Stretch" Text="{Binding PostAddress}"/>

                            <TextBlock Grid.Row="6" Grid.Column="0" Text="Country" />
                            <dxe:TextEdit Grid.Row="6" Grid.Column="2" Text="{Binding PostCountry}"/>

                            <TextBlock Grid.Row="4" Grid.Column="0" Text="City" />
                            <dxe:TextEdit Grid.Row="4" Grid.Column="2" MaxLength="100" Text="{Binding City}"/>

                            <TextBlock Grid.Row="8" Grid.Column="0" Text="Postal Code" />
                            <dxe:TextEdit Grid.Row="8" Grid.Column="2" MaxLength="15" Text="{Binding PostalCode}"/>

                            <TextBlock Grid.Row="10" Grid.Column="0" Text="Subdivision" />
                            <dxe:TextEdit Grid.Row="10" Grid.Column="2" MaxLength="100" Text="{Binding Subdivision}"/>

                            <TextBlock Grid.Row="0" Grid.Column="4" Text="Email" />
                            <dxe:TextEdit Grid.Row="0" Grid.Column="6" MaxLength="254" Text="{Binding Email1}"/>

                            <TextBlock Grid.Row="2" Grid.Column="4" Text="Phone" />
                            <dxe:TextEdit Grid.Row="2" Grid.Column="6" MaxLength="20" Text="{Binding Phone1}"/>

                            <TextBlock Grid.Row="4" Grid.Column="4" Text="Phone" />
                            <dxe:TextEdit Grid.Row="4" Grid.Column="6" MaxLength="20" Text="{Binding Phone2}"/>

                            <TextBlock Grid.Row="6" Grid.Column="4" Text="Fax" />
                            <dxe:TextEdit Grid.Row="6" Grid.Column="6" MaxLength="50" Text="{Binding Fax1}"/>

                            <TextBlock Grid.Row="8" Grid.Column="4" Text="Telex" />
                            <dxe:TextEdit Grid.Row="8" Grid.Column="6" MaxLength="100" Text="{Binding Telex}"/>

                            <TextBlock Grid.Row="10" Grid.Column="4" Text="Web" />
                            <dxe:TextEdit Grid.Row="10" Grid.Column="6" MaxLength="255" Text="{Binding Web}"/>

                        </Grid>
                    </DataTemplate>
                </dxg:GridColumn.CellTemplate>
            </dxg:GridColumn>
            <dxg:GridColumn FieldName="NewField"/>
        </dxg:GridControl.Columns>
    </dxg:GridControl>

In first cell I have few columns, I want to move cursor with in first cell and then jump to second cell.

Can someone please help. enter image description here My grid looks like above. I have focus on first field . On pressing tab I want focus move to City field not to next cell which is New Field.

Any suggestions?

  [1]: http://ift.tt/1QlRHry

C# collision: Bounce ball at 4 sides of a rectangle

I'm trying to make the an epic ping pong game, but there is one thing I don't get right.

PHOTO: http://ift.tt/1IfXHkg

If you look to the image, you can see that I have multiple rectangles in the middle of the canvas. The ball should bounce of it at all 4 sides. But whatever i am trying, i cant get it right.

I also want to change the following code with an IntersecWith code.

(yPos + bal.Width > recShapes.yPos && yPos < recShapes.yPos + recShapes.LandScapeRectangle.Width + 5)
                    &&
                    (xPos + bal.Height > recShapes.xPos && xPos < recShapes.xPos + recShapes.LandScapeRectangle.Height)

But I cant get the InterSect working, I get an error that says that there is no definition for IntersectsWith.

When the color of the ball is the same as the rectangle, the ball will go through the rectangle.

Don't throw to difficult things to me without explaining, i'm programming for not that long now :). I'm using WPF.

Thanks!

 protected void UpdateBall()
        {
            UpdatePlayers(mousePositionPlayerOne, AIposition);
            UpdateLandscape();

            // yPos and xPos are coordinates of the bal.
            yPos += yChange;
            xPos += xChange;

            bal.Margin = new Thickness(yPos, xPos, 0, 0);

            if (doubleBallSpeedEnable)
            {
                UpdatePlayers(mousePositionPlayerOne, AIposition);
                UpdateLandscape();

                yPos += yChange;
                xPos += xChange;

                bal.Margin = new Thickness(yPos, xPos, 0, 0);
            }


            PlayerDied();
        }

    if ((yPos + bal.Width > recShapes.yPos && yPos < recShapes.yPos + recShapes.LandScapeRectangle.Width + 5)
                        &&
                        (xPos + bal.Height > recShapes.xPos && xPos < recShapes.xPos + recShapes.LandScapeRectangle.Height)
                    && ((!(ballPlayerBrush.Color.Equals(recShapes.LandScapeBrush.Color))) && (!(ballPlayerBrush.Color.Equals(recShapes.LandScapeBrush.Color))) || recShapes.LandScapeBrush.Color.Equals(Colors.LimeGreen)))
                {
                    double left = Double.MaxValue;
                    double right = Double.MaxValue;
                    double top = Double.MaxValue;
                    double bot = Double.MaxValue;



                    if (yChange > 0)
                    {
                        left = recShapes.xPos - xPos + bal.Width / 2;
                        if (left < 0)
                            left = -left;
                    }
                    if (xChange > 0)
                    {
                        top = recShapes.yPos - yPos + bal.Height / 2 + 5;
                        if (top < 0)
                            top = -top;
                    }

                    if (yChange < 0)
                    {
                        right = xPos - recShapes.xPos +                           recShapes.LandScapeRectangle.Width + bal.Height / 2;
                        if (right < 0)
                            right = -right;
                    }
                    if (xChange < 0)
                    {
                        bot = yPos - recShapes.yPos + recShapes.LandScapeRectangle.Height + bal.Height / 2 + 5 ;
                        if (bot < 0)
                            bot = -bot;
                    }


                    Console.WriteLine("top: \t" + top);
                    Console.WriteLine("left: \t" + left);
                    Console.WriteLine("right: \t" + right);
                    Console.WriteLine("bot: \t" + bot);

                    double lowestNumber = Math.Min(Math.Min(Math.Min(bot, top), left), right);
                    Console.WriteLine("bigge: \t" + lowestNumber);

                    if (lowestNumber == bot)
                    {
                        xChange = -xChange;
                    }

                    if (lowestNumber == top)
                    {
                        xChange = -xChange;
                    }

                    if (lowestNumber == left)
                    {
                        yChange = -yChange;
                    }

                    if (lowestNumber == right)
                    {
                        yChange = -yChange;
                    }
                    delayAfterImpact = 0;



                    if (playerTwoHitBall)
                    {
                        recShapes.LandScapeRectangle.Fill = new SolidColorBrush(Colors.Blue);
                        recShapes.LandScapeBrush = new SolidColorBrush(Colors.Blue);
                    }else 
                    {
                        recShapes.LandScapeRectangle.Fill = new SolidColorBrush(Colors.Red);
                        recShapes.LandScapeBrush = new SolidColorBrush(Colors.Red);
                    }
                    //xChange = -xChange;

                } //<-- goede reset code!