1337475
1337475

Reputation: 171

C struct and pointer program does nothing when compiled. Displays no errors or warnings

I have this code and it isn't running for me. It doesn't give any errors or warnings. So I don't know what is wrong with it. I'm not too experienced with pointers in structs and I don't even know if that part of the code is causing it not to run.

I've used both Code::Blocks and DevC++ to compile it but neither worked any different.

It's a little long but it is only 3 functions. Nothing prints to the screen at all for me.

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

struct foo{
        int num;
        char *word;
        struct foo *ptr;
};
void func1(struct foo);
void func2(struct foo*);
void func3(struct foo);

int main() {
        struct foo a;
        a.num = 5;
        a.word ="myword";
        func1(a);
        printf("1 %d %s\n", a.num, a.word);

        a.num = 100;
        a.word = "secondword";
        func2(&a);
        printf("2 %d %s\n", a.num, a.word);

        a.ptr = &a;
        a.num = 50;
        a.word = "mylastword";
        func3(a);
        printf("4 %d %s\n", a.num, a.word);
}

void func1(struct foo a)
{
        while(*(a.word) != '\0');
        {
            putchar(*(a.word));
            a.word++;
        }
        putchar('\n');
        if(a.num % 10 != 0)
        {
            a.num *= 2;
        }
        a.word--;
        printf("num is %d\n", a.num);
}

void func2(struct foo *a)
{
        while(*(a->word) != '\0')
            { putchar(*(a->word));
              a->word++; }

                    putchar('\n');
        if(a->num % 10 != 0)
            { a->num *= 2; }
        a->word--;
        printf("num is %d\n", (*a).num);
}

void func3(struct foo a)
{
        if(a.num > a.ptr->num)
            { a.num = 500; }
        else
            { a.num = a.ptr->num +1; }
        a.word = "myotherword";
        a.ptr->word = "yetAnotherWord";
        printf("3 %d %s\n", a.num, a.word);
}

Any help would be much appreciated.

Thank you all.

Upvotes: 1

Views: 576

Answers (1)

Bill Lynch
Bill Lynch

Reputation: 81926

void func1(struct foo a)
{
    while(*(a.word) != '\0');

You should not have a semicolon after the while statement.

When fixed, it prints:

[4:58pm][wlynch@watermelon /tmp] ./foo
myword
num is 10
1 5 myword
secondword
num is 100
2 100 d
3 51 myotherword
4 50 yetAnotherWord

And to reinforce abelenky's comment, this took 3 seconds to discover with a debugger.

[4:59pm][wlynch@watermelon /tmp] g++ -g foo.cc -o foo
[4:59pm][wlynch@watermelon /tmp] gdb ./foo
GNU gdb 6.3.50-20050815 (Apple version gdb-1752) (Sat Jan 28 03:02:46 UTC 2012)

(gdb) run
Starting program: /private/tmp/foo 
Reading symbols for shared libraries ++......................... done
^C
Program received signal SIGINT, Interrupt.
func1 (a={num = 5, word = 0x100000e91 "myword", ptr = 0x7fff5fbffa58}) at foo.cc:34
34      while(*(a.word) != '\0');
(gdb)   

Upvotes: 8

Related Questions