COKEDUDE 27 Junior Poster in Training

I'm having trouble getting the parameters correct in my cat function. I would think since I'm changing temp that I would need to pass the address since I want to be able to see that in main. I think I'm getting screwed up by the decaying.

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

/* Swaps strings by swapping data*/
void swap2(char *str1, char *str2)
{
char *temp = (char *)malloc((strlen(str1) + 1) * sizeof(char));
strcpy(temp, str1);
strcpy(str1, str2);
strcpy(str2, temp);
free(temp);
} 

void cat(char *temp, char *strings_line_tokens[])
{
    strcat (temp,strings_line_tokens[1]);
    strcat (temp,strings_line_tokens[2]);
    strcat (temp,strings_line_tokens[3]);
}

int main()
{
    char str1[10] = "geeks";
    char str2[10] = "forgeeks";
    char temp[80] = {0};
    char *strings_line_tokens[503] = {0};
    int lower_bound_of_big_boy_counter = 0;

    strings_line_tokens[0] = malloc(strlen("string")+1);
    strcpy(strings_line_tokens[0], "string");

    strings_line_tokens[1] = malloc(strlen("string1")+1);
    strcpy(strings_line_tokens[1], "string1");

    strcpy (temp,strings_line_tokens[0]);
    lower_bound_of_big_boy_counter++;

    cat(&temp, strings_line_tokens)
    printf("temp is %s", temp);

    swap2(str1, str2);
    printf("str1 is %s, str2 is %s", str1, str2);
    getchar();
    return 0;
}
COKEDUDE 27 Junior Poster in Training

What are some good reasons for returning an address from a function?

COKEDUDE 27 Junior Poster in Training

I am trying to do Shortest Remaining Time scheduling algorithms turnaround time. This is the formula.

Turnaround Time = Completion Time - Arrival Time

I have already sorted my arrays.

This is what it looks like my hand.

5,1 done with magical 0
9,2 2nd iteration     1
2,4 1st iteration      2
0,7  done because first  3


0 to 7, 7 to 11, 11 to 12, 12 to 14

7          9        7           5

Turnaround Time = Completion Time - Arrival Time


1        3        2        4
0 to 7, 7 to 8, 8 to 12, 12 to 14
7         3       10      5

My issue is the backtracking to the 9,2. Since it hasn't arrived yet you have to skip it. 9 is the arrival time and 2 is how much time it takes to process. It has A LOT of print statements because I have been trying to figure out what is going on.

for(j = 1; j < i; j++)
    {
        printf("kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk \n");
        printf("j is %d abcd \n", j);
        printf("arrival_time_array is %d\n", arrival_time_array[1]);
        printf("time_cycles_required_for_job_array is %d\n", time_cycles_required_for_job_array[1]);
        printf("completion_time[1] above while: %d \n",completion_time[1]);
        printf("aaacompletion_time[j]: %d \n",completion_time[j]);
        printf("%d %d\n", magical_completion_time ,arrival_time_array[j]);
        printf("arrival_time_array[j] is %d \n", arrival_time_array[j]);
        printf("kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk \n");
        if(completed_flag[j] != 1)
        {
        printf("%d %d\n", completion_time[j] ,arrival_time_array[j]);
        printf("bbbcompletion_time[j]: %d \n",completion_time[j]);
        if(magical_completion_time >= arrival_time_array[j])
        {
            printf("j is %d \n", j);
            printf("%d %d\n", completion_time[j] ,arrival_time_array[j]);
            printf("arrival_time_array is %d\n", arrival_time_array[j]);
            printf("time_cycles_required_for_job_array is %d\n", time_cycles_required_for_job_array[j]);
            printf("completion_time[j] is %d\n", completion_time[j]);
            completion_time[j+1] = magical_completion_time + time_cycles_required_for_job_array[j+1];
            magical_completion_time = completion_time[j];
            completed_flag[j] = 1;
            printf("setting completed_flag[j] at j which is: %d …
COKEDUDE 27 Junior Poster in Training

Yes I know the code is not complete. I know it will cause an infinite loop.

The question is how would I break out of the first for loop and go to the second for loop? Wouldn't using break, break you out of everything? I only wanna break one level.

while(sjn_completion_time_flag != 1)
{
    for(j = 1; j < i; j++)
    {
        if(completed_flag[j] == 0 && completion_time[j] >= arrival_time_array[j])
        {
            printf("completion_time[j]: %d \n",completion_time[j]);
            printf("time_cycles_required_for_job_array[j]: %d \n",time_cycles_required_for_job_array[j]);
            completion_time[j] = completion_time[j] + time_cycles_required_for_job_array[j];
            completed_flag[j] == 1;
            //condition to break
            break;
        }
    }
    //for loop
}
COKEDUDE 27 Junior Poster in Training

BESIDES having to do a bunch of unnecessary iterations in a for loop with strlen doesn't it also produce weird behaviors?

http://www.cprogramming.com/tips/tip/dont-use-strlen-in-a-loop-condition

The documentation uses size_t instead of int. I believe I got weird behaviors when it happened. I didn't write it down when it happened so I can't remember where to look.

http://www.cplusplus.com/reference/cstring/strlen/
http://www.tutorialspoint.com/c_standard_library/c_function_strlen.htm

rproffitt commented: Hey, I like the question. +6
COKEDUDE 27 Junior Poster in Training

I have this print statement.

printf("(n * o ) % m == 0 is invalid so exiting. \n");

And this is the output.

(n * o ) Success == 0 is invalid so exiting.

I don't even have the word "Success" anywhere in my program. I don't see anything in the printf documentation about it treating m special.

http://www.cplusplus.com/reference/cstdio/printf/

COKEDUDE 27 Junior Poster in Training

Can someone please explain these errors? I don't have a multidimensional array so I don't understand how I'm getting this error.

main.c:291: warning: passing argument 2 of ‘type_specifier’ from incompatible pointer type
main.c:263: note: expected ‘int *’ but argument is of type ‘int **’
main.c:291: warning: passing argument 3 of ‘type_specifier’ from incompatible pointer type




void declaration_list(char *strings_line_tokens[], int *big_boy_counter, int *lower_bound_of_big_boy_counter)
{
    int cmp_str1 = 0;
    int cmp_str2 = 0;
    int cmp_str3 = 0;
    printf("declaration_list().\n");
    cmp_str1 = strcmp("int", strings_line_tokens[*lower_bound_of_big_boy_counter]);
    cmp_str2 = strcmp("float", strings_line_tokens[*lower_bound_of_big_boy_counter]);
    cmp_str3 = strcmp("void", strings_line_tokens[*lower_bound_of_big_boy_counter]);
    if(cmp_str1 == 0 || cmp_str2 == 0 || cmp_str3 == 0)
    {
        declaration(strings_line_tokens, &big_boy_counter, &lower_bound_of_big_boy_counter);
    }
    //declaration_prime();
    //declaration_list();
}

void program(char *strings_line_tokens[], int *big_boy_counter, int *lower_bound_of_big_boy_counter)
{
    int cmp_str1 = 0;
    int cmp_str2 = 0;
    int cmp_str3 = 0;
    printf("In program().\n");
    cmp_str1 = strcmp("int", strings_line_tokens[*lower_bound_of_big_boy_counter]);
    cmp_str2 = strcmp("float", strings_line_tokens[*lower_bound_of_big_boy_counter]);
    cmp_str3 = strcmp("void", strings_line_tokens[*lower_bound_of_big_boy_counter]);
    if(cmp_str1 == 0 || cmp_str2 == 0 || cmp_str3 == 0)
    {
        declaration_list(strings_line_tokens, &big_boy_counter, &lower_bound_of_big_boy_counter);
    }
}
COKEDUDE 27 Junior Poster in Training

@deceptikon I'm using C not C++ :(.

COKEDUDE 27 Junior Poster in Training

I'm getting infinite recursion here. I'm sorry if this is obvious but I don't see what I'm doing wrong here. program() gets called from main, then program() calls declaration_list(), then declaration_list() calls declaration(). I don't see how in the function declaration_list it ever calls declaration_list() again when right before that it calls declaration(), and declaration() never calls declaration_list().

void declaration()
{
    printf("declaration().\n");
}

void declaration_list()
{
    printf("declaration_list().\n");
    declaration();
    declaration_list();
}

void program()
{
    printf("In program().\n");
    declaration_list();
}
COKEDUDE 27 Junior Poster in Training

I am trying to pass the address of strings_line_tokens to split_string. I would think I would need the "&" for the address then one of these methods would work.

static void split_string(const char *buffer, size_t buflen, char ***strings_line_tokens)
static void split_string(const char *buffer, size_t buflen, char **strings_line_tokens)
static void split_string(const char *buffer, size_t buflen, char **strings_line_tokens[])
static void split_string(const char *buffer, size_t buflen, char ***strings_line_tokens[])

Here is my declaration and where I try to pass the address to the function.

char *strings_line_tokens[503] = {0};
split_string(line, strlen(line)+1, &strings_line_tokens);

I keep getting some variation of this error.

warning: passing argument 3 of ‘split_string’ from incompatible pointer type
main.c:73: note: expected ‘char **’ but argument is of type ‘char * ()[503]’

COKEDUDE 27 Junior Poster in Training

Yes I did read these two posts.

http://stackoverflow.com/questions/3082914/c-compile-error-variable-sized-object-may-not-be-initialized
http://stackoverflow.com/questions/14186879/c-error-variable-sized-object-may-not-be-initialized

My case is a bit different because I'm using char * ptr[buflen]. This is what I have tried:

char  *ptr[buflen] = {0};  //This gave me the variable sized object error. 

char  *ptr[buflen];
memset( ptr, 0, buflen*buflen*sizeof(char)); //I figured this would work with looking at the previous examples. 

//This seemed to work but I am curious if I need to use free or malloc
after looking at the previous examples. I don't want this to seg fault later
in the program and have no clue what is causing it. 
char  *ptr[buflen]; 
memset(ptr, 0, sizeof ptr);

char *strings_line_tokens[503] = {0}; //Why does this work but the above won't work? 
COKEDUDE 27 Junior Poster in Training

That makes sense :). Thank you.

COKEDUDE 27 Junior Poster in Training

Yes.

Are you saying my cast didn't work? That is why I casted it.

COKEDUDE 27 Junior Poster in Training

Is the ordering of checking if a number is between two values important? I figured this would be pretty simple to do but its not working.

if(0 <= (int)strings[p][0] && (int)strings[p][0] <= 9)
{
    printf ("NUM: %s\n",strings[p]);;
}
else
{
    printf ("ID: %s\n",strings[p]);
}
COKEDUDE 27 Junior Poster in Training

If you carefully look at this example you will see with atoi when it runs into a string it gives the integer value of 0. So I was wondering how you tell the difference between the integer value of 0 and a string that got converted to 0.

http://www.tutorialspoint.com/c_standard_library/c_function_atoi.htm

COKEDUDE 27 Junior Poster in Training

I like it when you ask it that way :).

When I have a 10 or 0. I figured I mixed up the logic and changed the or to an and but that didn't fix the problem.

COKEDUDE 27 Junior Poster in Training

I'm having trouble with the if statement. I have verified with print statements that (int)strings_line_tokens[l][m] == 0. I thought maybe my logic was backwards since I had two not statements with an or, so I changed it to an and. That didn't help either.

if((int)strings_line_tokens[l][m] != 10 || (int)strings_line_tokens[l][m] != 0)
{
    error_on_flag[strings_special_token_incrementer] = 1;
    //printf ("setting  error_on_flag[strings_special_token_incrementer] = 1 \n");
}



strings_line_tokens[l][m] is 0
setting  error_on_flag[strings_special_token_incrementer] = 1
COKEDUDE 27 Junior Poster in Training

Is there a way to split a string at different types of characters into separate strings?

char str[] ="(I) 44like22 .cookies. ,This, /is\ ?tricky?";

Something like this?

( I ) 44 like 22 . cookies . , This , / is \ ? tricky ?
COKEDUDE 27 Junior Poster in Training

I need to read a file that is completely random and do something based on whatever character I get. I can get any of these character types "/", "*", a string, or numbers. I need to do something different with each case. I think the best way would be to start with fgets and read line by line. After that I would usually use sscanf, but since the files I will be reading are completely random I'm not sure how to do this. This is what I have started with. Any ideas would be greatly appreciated :).

while(fgets(buffer, 80, fp) != NULL)
{
    /*if(/)
    {
        //do something for "/" character
    }
    if(*)
    {
        //do something for "*" character
    }
    if(string)
    {
        //do something for string
    }
    if(numbers)
    {
        //do something for numbers
    }*/
    memset(buffer, 0, 80);
}

Why is my text getting italisized?

COKEDUDE 27 Junior Poster in Training

I have seen both ways for reading file error messages. Is one better than the other? Is exit(0) better than return 1 or vice versa?

FILE *fp;
fp = fopen(argv[1], "r");                         //Open file for read.

if(!fp)
{
    printf("Error opening file %s!",argv[1]);    //Program prints error message and closes if file is not found.
    exit(0);
}




FILE *input;
input = fopen (argv[1],"r");
if (input == NULL)
{
    printf("Error while opening the file.\n");
    return 1;
}
COKEDUDE 27 Junior Poster in Training

This is the version info.

gcc version 4.4.7 20120313 (Red Hat 4.4.7-11) (GCC)

It looks quite old.

https://www.gnu.org/software/gcc/releases.html

How do I check if its c89 or c90?

COKEDUDE 27 Junior Poster in Training

This program goes against everything I have been taught and learned in C. How does this compile? Why does this not need to be int main? Why no return 0? Don't you need an initial declaration of sub() above main? That bugs the crap out of me. I like keeping my functions above main.

#include <stdio.h>

main()
{
   sub ();
   sub ();
}

sub()
{
   static int y = 5;
   printf(" y is %d \n",y);
   y++;
}
COKEDUDE 27 Junior Poster in Training

Your right :(. Keyboard shortcuts don't work the way you would expect. This method won't work.

    red1.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_X, ActionEvent.ALT_MASK));

You would have to use this method of keyboard shortcuts.

leftJustify.setAccelerator(KeyStroke.getKeyStroke('L', Toolkit
    .getDefaultToolkit().getMenuShortcutKeyMask()));

http://www.java2s.com/Code/Java/Swing-JFC/Aquickdemonstrationofcheckboxmenuitems.htm

COKEDUDE 27 Junior Poster in Training

I have seen these two methods of using ItemListener. I am curios which is better and why. What are the differences?

ItemListener a;
Choice ce = new Choice();
ce.addItemListener(a);



ItemListener itemlistener = new ItemListener();
itemlistener.handle = checkboxmenuitem;
checkboxmenuitem.addItemListener(itemlistener);
COKEDUDE 27 Junior Poster in Training

Will I get any weird errors with using JCheckBox in a menu? I have done that and it seems to be working.

COKEDUDE 27 Junior Poster in Training

I was looking at these two examples and I was curious what the difference is between JCheckBox and JCheckBoxMenuItem.

http://www.macs.hw.ac.uk/cs/java-swing-guidebook/?name=JMenuBar&page=3
https://docs.oracle.com/javase/tutorial/displayCode.html?code=https://docs.oracle.com/javase/tutorial/uiswing/examples/components/CheckBoxDemoProject/src/components/CheckBoxDemo.java

These pictures make it look they are the same except JCheckBox is not in a menu but it is easy to add to a menu with the menu_name.add(menu_item) command. Is that correct?

http://www.javaperspective.com/menus.html
http://www.tutorialspoint.com/swing/swing_jcheckbox.htm

COKEDUDE 27 Junior Poster in Training

Netbeans is picky about the order. When I moved this to the bottom of main it works as expected :).

f.setVisible(true);
COKEDUDE 27 Junior Poster in Training

I am having issue with jmenu popup in netbeans. It only sometimes works. Sometimes I don't get a java popup at all. Sometimes my File and Edit options are completely missing. This is what my code looks like.

import javax.swing.*;

public class menu {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        JFrame f = new JFrame();
        f.setVisible(true);
        f.setSize(400,400);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLocationRelativeTo(null);

        JMenuBar mb = new JMenuBar();

        JMenu file = new JMenu ("File");
        mb.add(file);
        JMenu edit = new JMenu("Edit");
        mb.add(edit);

        f.setJMenuBar(mb);
    }

}
COKEDUDE 27 Junior Poster in Training

If you want to set an entire array to -1 is better to cycle through it with a for loop like this?

for (int i = 0; i < 100; ++i){
  array[i] = -1;
}

Or use memset like this?

memset (array,-1,100);
COKEDUDE 27 Junior Poster in Training

Why am I not getting a segmentation fault or at least weird results with this array out of bounds? I'm a bit disappointed. One of the few times I actually want it to happen it won't happen.

int i = 0;
int j = 0; 
int n = 0; 
int a[50];
int frame_page[6];
int no = 0;
int k = 0;
int page_avl = 0;
int cont = 0;
printf("\n enter number\n");
scanf("%d",&n);
printf("\n enter number1 :\n");

for(i=1;i<=n;i++)
scanf("%d",&a[i]);

printf("\n enter number2 :");
scanf("%d",&no);

for(i=0;i<no;i++)
frame_page[i]= -1;
COKEDUDE 27 Junior Poster in Training

Where are the c programming variable name rules defined? I usually use these two websites for figuring out these kind of things but I don't see it anywhere.

http://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm
http://www.cplusplus.com/reference/cstdio/scanf/

COKEDUDE 27 Junior Poster in Training

Here is more code can anyone spot a problem?

if(manager_pid == 0)
{
    printf("Hello? \n");
    if(close(pipe1[READING]) != 0)
    {
        printf("Error in closing pipe1 \n");
    }
    if(close(pipe2[READING]) != 0)
    {
        printf("Error in closing pipe2 \n");
    }
    if(close(pipe3[WRITING]) != 0)
    {
        printf("Error in closing pipe \n");
    }
}
i = 0;
printf("work please \n");
//test_value = read(pipe3[READING], &boo, sizeof(echo));
//printf("test_value is %d \n", test_value);

while(i < 10)
{
    printf("In while \n");
    //printf("Hello?? \n");
    //test_value = read(pipe3[READING], &boo, sizeof(echo));
    //printf("test_value is %d \n", test_value);
    //printf("Entering infinite loop \n");
    //printf("i is %d \n", i);
    //nbytes = read(pipe3[0], array, 45);
    //printf("nbytes is %d \n", nbytes);
    //log_dat_fp = fopen(argv[2], "a");
    if(read(pipe3[READING], &message, sizeof(struct MESSAGE)) != -1)
    {
        printf("Entering if \n");
        log_dat_fp = fopen(argv[2], "a");
        printf("First if  \n");
        time(&current_time);
        //if(message.owner == 1 && (message.instruction == 'r' || message.instruction == 'R'))
        if(message.instruction == 'r' || message.instruction == 'R')
        {
            if(message.owner == 1)
            {
                printf("message.owner == 1 with r or R \n");
                fprintf(log_dat_fp, "Store Manager at time: %s received message %d %d %c %s", strtok(ctime(&current_time), "\n"), 
                message.owner, getpid(), message.instruction, message.id);
                pclose(log_dat_fp);
            }
            else if(message.owner == 2)
            {
                printf("message.owner == 2 with r or R  \n");
                fprintf(log_dat_fp, "Store Manager at time: %s received message %d %d %c %s", strtok(ctime(&current_time), "\n"), 
                message.owner, getpid(), message.instruction, message.id);
                pclose(log_dat_fp);
            }
            else
            {
                printf("You have junk  \n");
            }
        }
        else if(message.instruction == 'u' || message.instruction == 'U')
        {
            if(message.owner == 1)
            {
                printf("message.owner == 1 with u or U  \n");
                fprintf(log_dat_fp, "Store Manager at time: %s received message %d %d %c %s %d", strtok(ctime(&current_time), …
COKEDUDE 27 Junior Poster in Training

Can anyone tell me why I have an infinite loop when reading from a pipe?

i = 0;

while(i < 10)
{
    test_value = read(pipe3[READING], &message, sizeof(struct MESSAGE));
    printf("test_value is %d \n", test_value);
    //printf("Entering infinite loop \n");
    //printf("i is %d \n", i);
    //nbytes = read(pipe3[0], array, 45);
    //printf("nbytes is %d \n", nbytes);
    //log_dat_fp = fopen(argv[2], "a");
    if(read(pipe3[READING], &message, sizeof(struct MESSAGE)) != -1)
    {
        printf("First if  \n");
        time(&current_time);
        if(message.owner == 1 && (message.instruction == 'r' || message.instruction == 'R'))
        {
            printf("First if  \n");
            fprintf(log_dat_fp, "Store Manager at time: %s received message %d %d %c %s", strtok(ctime(&current_time), "\n"), 
            message.owner, child_pid2, message.instruction, message.id);
            pclose(log_dat_fp);
        }
    }
    else
    {
        printf("manager can't read from pipe\n");
        exit(1);
    } // read no good
    i++;
    log_dat_fp = fopen(argv[2], "a");
    printf("Each pass  \n");
}
COKEDUDE 27 Junior Poster in Training

What happens in this case? It was able to deal with the /n.

    while (fscanf(init_dat_fp, "%s %d",  nam, &val) !=EOF)
    {
        //sscanf(line1, "%s %s %x", label, mneumonic ,&start_address);
        init_name_table[counter] = malloc(strlen(nam)+1);
        strcpy(init_name_table[counter], nam);
        init_value_table[counter] = val;
        strcpy(table[counter].id, nam);
        table[counter].value = val;
        printf(" init_name_table[counter] is %s \n", init_name_table[counter]);
        printf(" init_value_table[counter] is %d \n", init_value_table[counter]);
        counter++;
        memset(nam, 0, 80);
        val = 0;
        table_size = counter;  
    }
COKEDUDE 27 Junior Poster in Training

I would like the fork to execute, then I would like all the activities in the while loop to take place in that child process, Then I want to send that stuff to the parent process. I'm not sure how to combine all these activities.

COKEDUDE 27 Junior Poster in Training

I have this if block that is supposed to be creating a pipe then forking and I would like to combine the while loop below it with it. How would I do that?

p = pipe(pipe1);
if (p < 0) {
    printf("pipe error");
    exit(0);
}
else
{
    printf("successful pipe1 = %d\n",p);
}
p = pipe(pipe2);
if (p < 0) 
{
    printf("pipe error");
    exit(0);
}
else
{
    printf("successful pipe2 = %d\n",p);
}
p = pipe(pipe3);
if (p < 0) 
{
    printf("pipe error");
    exit(0);
}
else
{
    printf("successful pipe3 = %d\n",p);
}

//If the parent wants to receive data from the child, it should close fd1, and the child should close fd0.
//If the parent wants to send data to the child, it should close fd0, and the child should close fd1. 
//Since descriptors are shared between the parent and child, we should always be sure to close the end 
//of pipe we aren't concerned with.
//On a technical note, the EOF will never be returned if the unnecessary ends of the pipe are not explicitly closed.     
if ((child_pid1 = fork()) == 0)
{
    if (close(pipe1[1]) == -1)
    {
       printf("close error closing pipe1[1]\n");
    }
    if (close(pipe2[0]) == -1)
    {
       printf("close error closing pipe2[0]\n");
    }


    printf("In the server child: reading file = %s\n\n", argv[1]);
}





while (fscanf(init_dat_fp, "%s %d",  nam, &val) !=EOF)
{
    //sscanf(line1, "%s %s %x", label, mneumonic ,&start_address);
    init_name_table[counter] = malloc(strlen(nam)+1);
    strcpy(init_name_table[counter], nam);
    init_value_table[counter] = val;
    printf(" init_name_table[counter] is %s \n", init_name_table[counter]);
    printf(" init_value_table[counter] is %d \n", init_value_table[counter]);
    counter++;
    memset(nam, …
COKEDUDE 27 Junior Poster in Training

Is this a good example of using multiple pipes. I need to fork 3 children. Would I just need to repeat the process in between the hyphens? Where would I add extra sleeps? Is it a bad idea to use WEXITSTATUS and WIFEXITED? Can anyone spot any errors?

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <errno.h>
#include <unistd.h>

typedef int fd; /* low-level Unix file descriptor */
typedef fd pipe_t[2]; /* a two-element array of fd's: one for input, one for output */
const int LINES=1000;

int main (int argc, char **argv) {
    int child_id;
    pipe_t mypipe;

    fprintf (stderr, "Here I am in the program!\n");

    if (pipe (mypipe) < 0) {
        perror ("Pipe creation");
        exit (errno);
        }
    fprintf (stderr, "Got pipe: fd's are %d (read) and %d (write)\n", mypipe[0], mypipe[1]);

    //-------------------------------------------------------------------------------------    
    child_id = fork();

    if (child_id) {
        FILE *outfile;
        int counter;
        int status;
        pid_t whodied;

        fprintf (stderr, "I'm the parent.\n");
        if (close (mypipe[0]) < 0) {
            perror ("close read end");
            exit (errno);
            }
        fprintf (stderr, "Successfully closed read end of pipe.\n");

        outfile = fdopen (mypipe[1], "w");
        if (! outfile) {
            perror ("fdopen");
            exit (errno);
            }
        fprintf (stderr, "Successfully opened write end as a FILE *.\n");

        for (counter=0; counter<LINES; ++counter) {
            fprintf (outfile, "Line %d\n", counter);
            }
        /* Another way to write to the  pipe... */
        write (mypipe[1], "Isn't this exciting?\n", 21);

        fprintf (stderr, "Finished writing to file.\n");

        fclose (outfile);
        /* necessary or the child will never get an EOF,
        so it'll never know it's time to die. …
COKEDUDE 27 Junior Poster in Training

I started off reading a file with fscanf. I figured I could use fscanf since the file was consistent with just two columns. I got very strange output when using fscanf. Can someone please explain why? When I switched over to fgets with sscanf it worked perfectly. I am curious why though. The only changes I made was switching the fscanf to fgets and adding the sscanf line.

//while (fscanf(trans1_fp, "%c %s",  &char_storage, nam) !=EOF)
while(fgets(line1, 80, trans1_fp) != NULL)
{
    sscanf(line1, "%c %s", &char_storage, nam);
    trans1_char[counter] = char_storage;
    trans1_char_table[counter] = malloc(strlen(nam)+1);
    strcpy(trans1_char_table[counter], nam);
    printf(" trans1_char[counter] is %c \n", trans1_char[counter]);
    printf(" trans1_char_table[counter] is %s \n", trans1_char_table[counter]);
    printf(" passing through second while loop \n");
    counter++;
    memset(nam, 0, 80);
    char_storage = 0;
    //memset(char_storage, 0, 80);
    val = 0; 
}

This is the output I was getting

 trans1_char[counter] is R
 trans1_char_table[counter] is XXXX
 passing through second while loop
 trans1_char[counter] is

 trans1_char_table[counter] is R
 passing through second while loop
 trans1_char[counter] is
 trans1_char_table[counter] is DISNEY
 passing through second while loop
 trans1_char[counter] is

 trans1_char_table[counter] is
 passing through second while loop

Here is the output I expect.

 trans1_char[counter] is R
 trans1_char_table[counter] is XXXX
 passing through second while loop
 trans1_char[counter] is R
 trans1_char_table[counter] is DISNEY
 passing through second while loop
COKEDUDE 27 Junior Poster in Training

I have used this several times in the past for writing to files. Is there a problem with this? I'm just writing text. I have never had any issues. What is the difference with the binary file? I thought binary files usually weren't readable. I read those two links and they don't really explain it.

FILE *init_dat_fp;

init_dat_fp = fopen (argv[1], "wb");

http://www.tutorialspoint.com/c_standard_library/c_function_fopen.htm
http://www.cplusplus.com/reference/cstdio/fopen/

COKEDUDE 27 Junior Poster in Training

Thank you for your patience in giving your very detailed explanation :).

I changed the malloc part, added the initialization part, fixed the del() function.

COKEDUDE 27 Junior Poster in Training

I changed the malloc part, added the initialization part, fixed the del() function. My priority is coming from the calculation of a distance formula. As you know when calculating the distance formula you don't always have have pretty numbers. You sometimes get long decimal numbers.

Why didn't it crash after removing like 20 numbers? I used this. The only real change I made to it was changing the malloc part because I got this warning. Was I just lucky or do you have to do something special to remove it?

warning: assignment from incompatible pointer type

   //new = ( N* ) malloc( sizeof( N ) );
    new = malloc( sizeof( N ) );

http://matrixsust.blogspot.com/2011/11/basic-priority-queue-in-c.html

COKEDUDE 27 Junior Poster in Training

I am using a priority queue with a double as the priority. I am guessing this is cause so issues. I used these numbers first with no issues.

34.365681
34.481879
34.539832
36.715120

I then used these numbers and had a segmentation fault.

45.411042
40.481879
37.702110
38.951187

struct PRIORITYQUEUE
    {
    int x_pq; 
    int y_pq;
    double heuristic_pq;
    int priority;
    int info;
    struct PRIORITYQUEUE *next;
}*start, *q, *temp, *new;

typedef struct PRIORITYQUEUE *N;

void insert(int x, int y, double heuristic)
{

    int item; 
    double itprio;
    //new = ( N* ) malloc( sizeof( N ) );
    new = malloc( sizeof( N ) );

    itprio = heuristic;
    new->x_pq = x;
    new->y_pq = y;
    new->heuristic_pq = itprio;

    if ( start == NULL || itprio < start->heuristic_pq )
    {
        new->next = start;
        start = new;
    }
    else
        {
            q = start;
            while ( q->next != NULL && q->next->heuristic_pq <= itprio )
                q = q->next;

            new->next = q->next;
            q->next = new;
        }
}

void del()
{
    if ( start == NULL )
    {
         printf( "\nQUEUE UNDERFLOW\n" );
    }
    else
    {
    new = start;
    printf( "\nDELETED ITEM IS %d\n", new->info );
    start = start->next;
    free( start );

    }

}

void display()
{
    temp = start;
    if ( start == NULL )
        printf( "QUEUE IS EMPTY\n" );

    else
    {
        printf( "QUEUE IS:\n" );

        while ( temp != NULL )
        {
            printf( "\t x is %d y is %d[heuristic=%lf] \n", temp->x_pq, temp->y_pq, temp->heuristic_pq );
            temp = temp->next;
        }
     }
}
COKEDUDE 27 Junior Poster in Training

I was reading this example of Priority queues and have several questions.

http://matrixsust.blogspot.com/2011/11/basic-priority-queue-in-c.html

#include<stdio.h>
#include<malloc.h>

void insert();
void del();
void display();


//How exactly do structs in structs work? Do you need to do anything special with them? Is this a //form of a linked list? Which part of this is set to NULL? A lot of the comparisons later on are // to NULL. Were the node names made as pointers to make them easier to pass to functions later on? 
//Do you really need to make them pointers? Do you really need that many names? 
struct node
    {

        int priority;
        int info;
        struct node *next;
    }*start, *q, *temp, *new;

//Why was this declared as typedef? I thought you only use typedef if you want to reuse a type more //easily. 
typedef struct node *N;

int main()
{
    int ch;

    do
     {
            printf( "\n[1] INSERTION\t[2] DELETION\t[3] DISPLAY [4] EXIT\t:" );
            scanf( "%d", &ch );
            while(ch > 4)
            {
                printf( "\n[1] INSERTION\t[2] DELETION\t[3] DISPLAY [4] EXIT\t:" );
                scanf( "%d", &ch );
            }

            switch ( ch )
                {
                case 1:
                    insert();
                    break;
                case 2:
                    del();
                    break;
                case 3:
                    display();
                    break;
                case 4:
                    break;
                }
        }

    while ( ch < 4 );
    return 0;
}



void insert()
{

    int item, itprio;
    //Is new being initialized to NULL? 
    new = ( N* ) malloc( sizeof( N ) );

    printf( "ENTER THE ELT.TO BE INSERTED :\t" );
    scanf( "%d", &item );
    printf( "ENTER ITS PRIORITY :\t" );
    scanf( "%d", &itprio );
    //The …
COKEDUDE 27 Junior Poster in Training

Yes. I screwed up a comma in a pass to my function. Google wasn't giving me any useful results so I assumed it was a casting issue. I also couldn't find any examples of casting a struct value either

error: invalid operands to binary & (have ‘double’ and ‘double’)
COKEDUDE 27 Junior Poster in Training

I am trying to cast an int value in a struct to a double. I am guessing I am screwing up the parenthesis somehow. I wasn't able to find anything useful in the forum or in google.

struct START
{
    int x; 
    int y;
    double heuristic;
};

struct SHAPES
{
    int x [100]; 
    int y [100];
    double heuristic [100];
    int has_visited [100];
    int num_points;
    int *link;
};

struct LINE
{
    int x1 [100];
    int y1 [100];
    int x2 [100];
    int y2 [100];
};

double addition(double x, double y)
{
    return x + y;
}

int main(int argc, char *argv[])
{
    int kk = 0;
    double x = 0;
    double y = 0;
    double z = 0;    
    struct START start;
    struct END end;
    struct SHAPES shapes[100];
    struct LINE edges;


    x = (double)start.x;
    y = (double)edges.x1[kk];
    z = addition((double)start.x, (double)edges.x1[kk])
   return 0; 
}
COKEDUDE 27 Junior Poster in Training

I need some ideas on my array of struct implementation. This is what I have in my structs. I plan on making SHAPES an array because I will have multiple SHAPES. Each shape will have multiple x and y coordinates. Because of this I'm not sure if should make a linked list or not.

struct START
{
    int x; 
    int y;
};
struct END
{
    int x; 
    int y;
};
struct SHAPES
{
    int x [100]; 
    int y [100];
    int *link;
};
struct DISTANCE
{
    int distance_traveled; 
    int distance_to_finish;
};

I was reading this and was wondering if I needed to malloc or calloc my structs as I create them. If so why and if not why? Malloc and calloc are always confusing to me.

http://stackoverflow.com/questions/10468128/how-do-you-make-an-array-of-structs-in-c/24542015#24542015

int main(int argc, char *argv[])
{

    //Is it better to make these pointers? 
    struct START start;
    struct END end;
    struct SHAPES shapes[100];

    while(fgets(line, 80, fp) != NULL)
    {
        //I have a very annoying issue here, I don't know the size of the lines. 
        //If there are more values I want to increment the x[] and y[] array but NOT the 
        //shapes array. I can only think of one way to deal with this by putting a bunch of 
        //variables in the sscanf. I discovered putting sscanf on the next line didn't do what 
        //I was hoping for. 
        sscanf(line, "%d%*c %d%*c ", &shapes[i].x[i] , &shapes[i].y[i] );
        printf(" line is: %s \n", line);
        sscanf(line, "%d%*c %d%*c ", &x1_main , &y1_main ); …
COKEDUDE 27 Junior Poster in Training

What about this part? How do you handle this?

No-throw guarantee: this function never throws exceptions.

If str does not point to a valid C-string, or if endptr does not point to a valid pointer object, it causes undefined behavior.

http://www.cplusplus.com/reference/cstdlib/strtol/

COKEDUDE 27 Junior Poster in Training

Whats wrong with atoi? I have used it in the past with no issues. Why is strtol better?

COKEDUDE 27 Junior Poster in Training

I know this works as expected if your command line arguments are strings.

#include <stdio.h>

int main( int argc, char *argv[] )  
{
   printf("Program name %sn", argv[0]);

if( argc == 2 )
{
   printf("The argument supplied is %sn", argv[1]);
}
   else if( argc > 2 )
{
   printf("Too many arguments supplied.n");
}
else
{
   printf("One argument expected.n");
}
}

Would you be able to do something similar to this if you have integers or would you need to use the first method then convert it with atoi?

#include <stdio.h>

int main( int argc, int *argv[] )  
{
   printf("Program name %sn", argv[0]);

if( argc == 2 )
{
   printf("The argument supplied is %sn", argv[1]);
}
   else if( argc > 2 )
{
   printf("Too many arguments supplied.n");
}
else
{
   printf("One argument expected.n");
}
}
COKEDUDE 27 Junior Poster in Training

If I would have used calloc would I of still had to initialize strings? Would something like that have worked? From what I have been reading about calloc it sounds like it would have done it for me.

strings[hash] = calloc(strlen(mneumonic)+1);