-2

Ok, I'm a bit stuck with malloc and structs it seems >P

#include ****
#include "func.h"

int main()
{
  struct fileData *fileData = (struct fileData*)malloc(sizeof(struct fileData));
  fileData->filePath = "text";
  printf(%c\n, *fileData->filePath);
}

In the func.h file:

#ifndef func
#define func

typedef struct fileData
{
  char *filePath;
  char *input;
  int *numbers;
}

It only prints the first 'T' then the program stops, I cant figure out how its supposed to be, I've tried for a while now haha

what I want to do is having a struct that contains a file path picked after the program is run, then read that text file and fill char *input with the whole input then collect all the numbers from input and store it as int in numbers.. I already have the functions running tho.. i can read from a file, i just have problem getting the struct running.

Martin G
  • 17,357
  • 9
  • 82
  • 98
Arro
  • 7
  • 2
  • Read the documentation, %c is character. use %s. :) – Stolas Apr 25 '14 at 09:00
  • In the h file you have struc, should be struct. That's a typedef, so you don't need struct keyword in c file. Your print has a %c format specifier, should be %s. Fix those and it should be pretty right. If you still have issues I can give a complete answer. – ntremble Apr 25 '14 at 09:05
  • thanks, it was ofc the %s that should be there, and what made me so confused was another bug caused by an uninitiated variable. thanks for the help – Arro Apr 25 '14 at 12:53

1 Answers1

2

This:

printf(%c\n, *fileData->filePath);

won't compile, you don't have any quotes around the first argument.

Fixing that, we get:

printf("%c\n", *fileData->filePath);

which will print exactly one character, the character found by following the fileData->filePath pointer.

If you wanted to print the full name, you should use %s:

printf("%s\n", fileData->filePath);

Note how the asterisk was dropped, since now we pass the address of the string's first character to printf().

Also, please don't cast the return value of malloc() in C.

Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606
  • `fileData->filePath ="text";` Is this OK?? – 0xF1 Apr 25 '14 at 09:02
  • @MadHatter Yes, but you should make `filePath` have the type `const char *` to clarify that it is meant to point at string literals. If the string is acquired at run-time, you must think about memory ownership. – unwind Apr 25 '14 at 09:04
  • thanks for the answer, the"" was left out cause i retyped the code and simply forgot em. I was kind of tired and missed an unititated variable that caused some wierd stuff to happen. its fixed and all the suggestions like not casting is implemented, thanks – Arro Apr 25 '14 at 12:54