Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer on Struct used in function

Tags:

c

pointers

struct

I have some problems in C with pointers and structs: I have 2 entities of the struct Signal and the pointer activeSignal to store one of the entities. Now, I want to use this "stored" entity in my function printParameters() to print the values of my struct. Unfortunately, my microcontroller-display prints some hieroglyphics instead of my value. I have to admit that I am not completely looking through pointer-arithmetic...

struct SigParameter {
  char *name;
  int value;
};

struct Signal {
  struct SigParameter signalchar;
};

int main(void) {
  struct Signal s1;
  struct Signal s2;
  s1.signalchar.name = "Sinus";
  s2.signalchar.name = "Rect";
  struct Signal *activeSignal = &s1;

  printParameters(activeSignal);
}

void printParameters(struct Signal *s) {
  lcdPrintf(0,11,9,"%s", s->signalchar.name);
}
like image 671
Julian Avatar asked Dec 09 '14 13:12

Julian


1 Answers

Here, there are some minor mistakes in your code. I believe those are typos.

  1. No forward declaration for printParameters().
  2. in your main() , function called is printParameter() which should be printParameters().
  3. missing semicolon after struct SigParameter signalchar

However, i don't see a,logic for using the struct Signal *activeSignal = &s1; if you simply want to print the value.

You can check the below code.

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


struct SigParameter {
 char *name;
 int value;
};

 struct Signal {
 struct SigParameter signalchar;
};

void printParameters(struct Signal s);

int main(void) {
 struct Signal s1;
 struct Signal s2;
 s1.signalchar.name = "Sinus";
 s2.signalchar.name = "Rect";

 printParameters(s2);
    return 0;
}

void printParameters(struct Signal s) {
    printf("%s\n", s.signalchar.name);
}

I have used simple printf() instead of your lcdPrintf(), but it works fine.

Output:

[sourav@broadsword temp]$ ./a.out

Rect

like image 122
Sourav Ghosh Avatar answered Nov 11 '22 04:11

Sourav Ghosh