-2

I am learning C language now and I do not know why an error occurred. Can someone help?

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

int main() {

struct TestData {
int * a;
};

struct TestData * p1 = (struct TestData *)malloc(sizeof(struct TestData));

void Data(struct TestData * addstruct) {
    int b;
    addstruct->a = &b;
}//Here are two errors, error code:C2601, E0065

Data(p1);
printf("%p", p1);
free(p1);
return 0;
}
  • 2
    You want to make `addstruct->a` point to `b`, but what happens to `b` at the end of `void Data`? – Blaze Feb 22 '19 at 14:14
  • 3
    Where do those error codes come from? What is the **exact** text of the errors? – dbush Feb 22 '19 at 14:16

2 Answers2

3

In standard C there are no local functions. You need to move the Data function out of main.

You probably want this:

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

struct TestData {
  int * a;
};

void Data(struct TestData * addstruct) {
  int b;
  addstruct->a = &b;
}

int main() {
  struct TestData * p1 = (struct TestData *)malloc(sizeof(struct TestData));

  Data(p1);
  printf("%p", (void*)p1);  // %p needs casting to (void*)
  free(p1);
  return 0;
}

This code compiles correctly, but there is another problem:

void Data(struct TestData * addstruct) {
  int b;
  addstruct->a = &b;
}

You put the pointer to the local variable b into addstruct->a, but as soon as the Data is finished, b no longer exists and addstruct->a therefore points to junk.

Read also following SO articles:

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • `Data` could be `static void Data(struct TestData * addstruct)` however, making it a function local to the file. – Lundin Feb 22 '19 at 14:17
  • @Jabberwocky No need to edit - I'm just pointing out that the concept of local functions does exist, just with a different meaning than what the OP attempted. – Lundin Feb 22 '19 at 14:20
  • Thank you for your sincere reply. Declaring it as a global function solves it. – Culus Homun Feb 22 '19 at 15:07
  • @CulusHomun you're supposed to accept the answer by clicking the grey checkmark on top left of the answer. So other people know that it was useful. – Jabberwocky Feb 22 '19 at 15:10
0

In standard C yon cannot create functions inside other functions. You need to move the Data function out of main.

Looks something like this, also add some C-style:

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

struct _TestData {
  int * a;
};

typedef struct _TestData TestData;

void Data(TestData* addstruct);

int main() {
 TestData* p1 = (TestData*)malloc(sizeof(TestData));
 int test_b = 100;
 Data(p1,test_b);
 printf("%p", (void*)p1);  // %p needs casting to (void*)
 free(p1);

 return 0;
}
/* You try put local pointer , after this function it will point to junk*/
/* I have changed Data function , add one arg now, it will work */
void Data(TestData* addstruct,int* test_b) {
  addstruct->a = test_b;
  return;
}