Fscanf failiure - c

I need to get name from the file (string).
But certainly it gets (null) value.
void dealer__init(){
FILE * dealer = fopen(DEALER_L, "r");
fscanf(dealer, "%d %d %255s", &my_og.money, &my_og.check_ok, my_og.name);
printf("%255s\n", my_og.name);
printf("%d\n", my_og.money);
printf("%d\n", my_og.check_ok);
if(money_at_beg == true && my_og.check_ok == 0){
my_og.money = MONEY_AT_BEG_INT;
my_og.check_ok = 1;
dealer__save();
}
printf("My name is set to: %s", &my_og.name);
fclose(dealer);
}
My file:
3000 1 dimitar
My struct:
struct dealer{
int money;
int check_ok;
char *name;
}my_og;

You can't use the fscanf function (or most other functions)1 to read data into an uninitialized – or invalid – pointer. That causes undefined behaviour which, in your case, appears to go unnoticed until you try to print out the value after the attempted read. (This is one of the nastier aspects of UB: that the code appears to work.)
You need to either explicitly allocate some memory to which your pointer refers to, like this:
my_og.name = malloc(256); // Allocate some memory
Or, perhaps simpler, declare the name member as a fixed-size array, rather than a pointer:
struct dealer{
int money;
int check_ok;
char name[256]; // 'allocated' when the structure is declared
}my_og;
1 There is, I believe a non-standard (POSIX) version of the scanf formatting option (%ms) that automatically allocates memory, but I would personally avoid such things like the plague. See: scanf dynamic allocation.

Related

printing struct member using user input

So I've been looking at structures, functions and pointers for days now. I just cant wrap my head around structures good enough to do what I want...
I was trying to write a function, which was originally going to receive user input (taken with fgets) as an argument. I have put that aside now, and just decided to give the function a single argument. That argument will be the name of a struct, and I'll use that name to access it's variables and print them the way I want.
typedef struct
{
int hp;
char *name;
} bare;
bare example;
void print_info(char *name);
int main()
{
example.hp = 5;
strcpy(example.name,"John");
print_info("example");
}
void print_info(char *name)
{
printf("The hp of %s is %d", (*name), (*name)->hp);
}
Whatever bloody thing I put there instead of char *name, it always ended up giving me the error "error: struct or union expected"! I tried struct bare **name and (*name)->hp/(*name).hp, char *name/**name and *&name.hp, *&name->hp, every possible solution I could think of..! i think they all turned out to be nonsense... I just cant wrap my head around pointers and structs enough to do this! A little help please? I searched high and low on function arguments, pointers and structs, yet couldn't find a solution/question like mine..
First, it's better to declare your struct this way:
typedef struct bare {
int hp;
char *name;
} bare;
Second, avoid global variable as much as you can. I don't see the point of declaring example in the global namespace since you are using it only inside main().
Third, this line has a problem:
strcpy(example.name, "John");
You are attempting to copy "John" to an uninitialized pointer (example.name) that points to some random memory address. You have to either allocate enough space using malloc() (and free it when you're done with it), or use a fixed-length array. Moreover, it's better to use strncpy() because it allows to specify the maximum number of characters to copy. This way you avoid the risk of buffer overflow.
Fourth, to avoid copying your entire struct to print_info() (in fact, any other struct to any other function), you should pass its address.
With all that said, here is how your code should be written:
#include <stdio.h>
#include <string.h>
typedef struct bare {
int hp;
char name[100]; // Make sure it has enough space, or use malloc() if you don't know how much it will hold initially
} bare;
void print_info(bare *name);
int main(void)
{
bare example; // Declare it inside main()
example.hp = 5;
strncpy(example.name, "John", sizeof example.name); // This works and is safe
print_info(&example);
}
void print_info(bare *name)
{
printf("The hp of %s is %d", name->name, name->hp);
}
Output:
The hp of John is 5
I think what you wish to do is this:
#include <stdio.h>
#include <string.h>
typedef struct {
int hp;
char *name;
} bare;
bare example;
void print_info(bare *name);
int main() {
example.hp = 5;
strcpy(example.name, "John");
print_info(&example);
}
void print_info(bare *name) {
printf("The hp of %s is %d", name->name, name->hp);
}
Or if you want to pass example by value:
#include <stdio.h>
#include <string.h>
typedef struct {
int hp;
char *name;
} bare;
bare example;
void print_info(bare name);
int main() {
example.hp = 5;
strcpy(example.name, "John");
print_info(example);
}
void print_info(bare name) {
printf("The hp of %s is %d", name.name, name.hp);
}
Why did your code not work?
print_info had an incorrect argument data type. What you wanted was to pass an object of bare or perhaps a pointer to an object of bare, but you were instead passing a variable of type char *.
The arrow operator is used on pointers. Maybe take a look at Arrow operator (->) usage in C.
You wanted to pass in a string typed in by the user.
I was trying to write a function, which was originally going to receive user input (taken with fgets) as an argument. I have put that aside now, and just decided to give the function a single argument.
This explains why you pass in a char * to your function. The input value was originally going to be read from fgets. In your program, you passed in the name of your variable.
bare example;
/* ... */
print_info("example");
To do a dynamic lookup on a symbol name, use dlsym.
As I suggested in comments, if you want to be able to look up the name of a variable to find the associated object, you can use dlsym so long as you are on a POSIX system (like Linux). For example:
// Need to inlcude <dlfcn.h> and link with -ldl
// Make local variables findable with -rdynamic
void print_info(char *name)
{
bare *p = dlsym(0, name);
if (p != NULL)
printf("The hp of %s is %d", p->name, p->hp);
else
printf("%s not found!\n", name);
}
So long as you include <dlfcn.h> and use -ldl when linking the program, and you make your symbol table visible (with -rdynamic on GCC), the program will find the pointer to your example variable. (Try it online!)
But you probably meant to do a lookup by name.
However, you seemed to have mixed some things up. Usually, the user will not care what names you have used for the variables in your program. You would never expect fgets to give you "example" because that is not what the user would type in.
You probably meant to search for the bare record that matches the name parameter of bare. In your case, "John".
print_info("John");
Normally, you would have a table of bares that you would look over and check for a match. However, in your simplified example, there is only one to check.
bare * find_bare(char *name)
{
if (strcmp(name, example.name) == 0) return &example;
return NULL;
}
void print_info(char *name)
{
bare *p = find_bare(name);
if (p != NULL)
printf("The hp of %s is %d", p->name, p->hp);
else
printf("%s not found!\n", name);
}
It isn't hard to create and search a table of bare.
In this case, you could probably simple create an array of bare to represent your collection that you would search over.
#define BARE_TABLE_SIZE 50
bare table_example[BARE_TABLE_SIZE];
Assuming you add the code to populate your table, you could use a simple loop to search for a matching name.
bare * find_bare(char *name)
{
for (int i = 0; i < BARE_TABLE_SIZE; ++i)
{
if (strcmp(name, table_example[i].name) == 0)
return &table_example[i];
}
return NULL;
}
Your example.name was an uninitialized pointer.
Finally, the most egregious error in your program is the attempt to call strcpy on an uninitialized pointer. One solution is to allocate new memory to hold the new name and assign the location of the new name to the pointer. POSIX systems (like Linux) supply a function called strdup that creates a copy of the input for you, in newly allocated memory.
example.name = strdup("John");
Since the memory is allocated by malloc, you would need to call free on the pointer if example is ever recycled for a new name.

Why does printf behave this way when using struct?

I am writing a code while making the use of structures. I am new to structs so I am practicing to get used to it. Anyway while trying to use printf on a variable of type string which is a variable of a struct type, printf only prints '#' instead of the whole string.
...
void signPlayers(struct player players[9], int playersC) // players is an array declared on main and playersC is the size of it.
{
for (int i = 0; i < playersC; i++)
{
char tname[22];
printf("Please enter the name of the player #%d: \n",i+1);
int res = scanf(" %s",&tname);
while(res != 1)
{
printf("Please enter a valid name for player #%d: \n",i+1);
res = scanf(" %s",&tname);
}
players[i].name = tname;
printf("Player #%d signed as %s!\n\n",players[i].id,players[i].name); // this printf actually works fine
}
}
int checkForWinner(struct player players[], int playersC)
{
for (int i = 0; i < playersC; i++)
{
if (players[i].pos == 10)
return 0;
printf("%s\n",players[i].name); // prints "#" instead of the name
}
return 1;
}
...
so If I entered the name Joey, At first printf it actually prints "Joey", then when I call the checkForWinner function (Its called after signPlayers function), the printf now prints only "#" instead of the whole name again.
What could be wrong?
Your code is attempting to access stack memory after the function has returned. When you do that, you get just whatever garbage was left over after the function call, or perhaps some part of a new stack frame belonging to a different function. Either way, it's undefined behavior.
There are several problems with the assignment players[i].name = tname; in function signPlayers:
It is assigning the address of the local array variable tname. This variable goes out of scope on every iteration through the loop. That means accessing that pointer after the loop will be undefined behavior.
Even if tname was moved out of the loop's scope up to the function scope, it will still go out of scope as soon as the function returns. Either way, accessing it after the function call is undefined behavior.
It's likely that the address of tname doesn't change from one iteration of the loop to the next. So that means that the .name member of every player in the players array will probably be identical (as well as being invalid).
There are many ways to fix this. Here are three ways:
Make a copy of tname each time through the loop using strdup(tname), and assign that to players[i].name:
players[i].name = strdup(tname);
The strdup function allocates memory, so if you use this approach, you will need to remember to free the .name member of each player when you're done.
Allocate memory dynamically to each players[i].name prior to calling signPlayers:
for (i=0; i<playersC; ++i) players[i].name = malloc(22);
signPlayers(players, playersC);
// Don't forget to call free() on each .name member after you're done
Inside signPlayers, you would then get rid of tname altogether and do:
int res = scanf(" %s", players[i].name);
Note: No need to do 22 * sizeof(char) here, since the C standard guarantees sizeof(char) == 1. Also, I used 22 because that's what OP's code uses to declare tname. However, it should be noted that scanf is less than ideal here, because it gives no way to limit the number of bytes written to the array, and thus no way to protect against buffer overflow. If you type a name longer than 21 characters (need to leave 1 byte for the null terminator), then you will overflow tname and your program will either crash or silently corrupt your data.
Turn players[i].name into a sized char array instead of just a char pointer. In other words, statically allocate memory to each players[i].name. This has the advantage of not needing to call free, as you would need to do with methods 1 and 2. OP didn't show the definition of struct player, but this should suffice for example purposes:
struct player {
char name[22];
// other stuff
};
And again, inside signPlayers, you would scanf directly into players[i].name instead of using tname.

how to put different type of data types in a Array dynamic in C

i try to store name and age in a dynamic array
when we have a different type of data , int , and Char that we dont know the size in the start how to use a dynamic array to store the 2 types
typedef struct personne{
char nom ;
int age ;
}personne;
struct personne saisie_personne_suivante(struct personne* x){
scanf("%s",&x->nom);
scanf("%d",&x->age);
return *x;
}
int main(void){
personne *ali;
ali = malloc(sizeof(char*));
saisie_personne_suivante(ali);
printf("\n %d ",ali->age);
printf("\n %s",&ali->nom);
return 0;
}
Why i dont sucess ?
i think we cant store two types of data at a time in array.If we do so we need to allocate half of memory to char and half to integers provided you should give some size of array.
=>in your program at this line [ali = malloc(sizeof(char*))] you are passsing address of only char not of variable.If you want to store both values just pass address of both int and char.
ali is a pointer to a struct of size sizeof(char) + sizeof(int) which may vary between architectures.
For the time being, let's assume it's 5 bytes (which it probably is on your PC).
What you're doing, is allocate space equal to size of a pointer to char, (which is either 32 or 64bits wide, depending on your OS).
What you probably want to do is allocate space equal to size of your struct (5 bytes), that is:
ali = malloc(sizeof(personne));
Note the lack of *, since you want actual memory for a struct and not a pointer pointing to such a location.
By the way, you wouldn't want to write: malloc(sizeof(char)) either, since that would be just one byte needed for your struct.
I strongly advise you to get your hands on a book on C or a decent tutorial at least.
int main() {
personne *ali;
ali = (struct personne *)malloc(sizeof(personne));
saisie_personne_suivante(ali);
printf("\n %d ", ali->age);
printf("\n %c", ali->nom);
return 0;
}
There is not enough memory for struct personne, so you need to malloc sizeof(personne) memory. nom is not a pointer,it's a char variable,when you print it, use printf("%c",ali->nom);
I can concur with the commenters who recommended a good book/tutorial to get started but nevertheless: here is your repaired code, with a bit of comment.
// printf(), fprintf(), and puts()
#include <stdio.h>
// exit(), malloc(), and scanf()
#include <stdlib.h>
#define PERSONNE_ERROR 0
#define PERSONNE_OK 1
typedef struct personne {
// fixed width for 49 characters and the trailing NUL
char nom[50];
int age;
} personne;
int saisie_personne_suivante(struct personne *x)
{
// For the returns of the scanf()s.
// Because you always check the returns if available
// (well, actually: the returns of printf() et al. rarely get checked)
// preset it to a value meant to say "OK"
int res = PERSONNE_OK;
// UX: let the users know what they are supposed to do.
puts("Your name, please");
// we have a fixed maximum size of name and we can set it here within scanf()
// scanf() returns the number of elements it parsed, *not* the number of characters
// sacnf() needs a pointer to the memory it is expected to put the value into.
// x->nom is already a pointer to a char array, no need to use "&"
if ((res = scanf("%49s", x->nom)) != 1) {
// we can return immediatly here.
// If we would need to cleanup (free memory, for example) we would
// set res to PERSONNE_ERROR and use a goto to jump at the place
// where all the cleanup happens. But that should be done if the clean-up
// is always the same (or could be sorted) and you need such cleanups
// more than just two or three times.
return PERSONNE_ERROR;
}
puts("Your age, too, if you don't mind.");
// x->age is not a pointer to an int, hence we need to prefix "&"
if ((res = scanf("%d", &x->age)) != 1) {
return PERSONNE_ERROR;
}
return res;
}
int main(void)
{
personne *ali;
int res;
// reserve momory for the struct
ali = malloc(sizeof(personne));
// call function that fills the struct and check the return
if ((res = saisie_personne_suivante(ali)) != PERSONNE_OK) {
fprintf(stderr, "Something went wrong with saisie_personne_suivante()\n");
exit(EXIT_FAILURE);
}
// print the content of struct personne
// you can feed printf() directly, no need to find the pointer to the memory
// holding the int
printf("Age: %d\n", ali->age);
// To print strings it needs to know the start of the string whcih needs to be
// a pointer and ali->nom is a pointer to the start of the string
printf("Name: %s\n", ali->nom);
// free allocated memory (not really necessary at the end of the
// program but it's deemed good style and because it costs us nothing
// we cannot find a good reason to skip it)
free(ali);
// exit with a value that tells the OS that this programm ended without an error
// It shoudl be 0 (zero) which it almost always is.
// *Almost* always
exit(EXIT_SUCCESS);
}
But really: go and get some beginners book/tutorial. I cannot give you a recommendation because I don't know about any good ones in your native language (sometimes the english version is good but the translation lacks a lot).

Returning a pointer of string arrays from a function

So i need help returning a pointer of string arrays from a function obtained from a file. The strings being no larger than 10.
Input file:
3
102
A3B
50
The first number being how many strings I need, the following numbers being what I need to store in the strings.
The function:
char ** buildArray(){
int x, i;
fscanf(fp, "%d", &x);
char answer[x][10];
for(i=0; i<x; i++){
fscanf(fp, "%s", answer[i]);
}
return answer;
}
I can get the values to be stored on the string array 'answer' properly, i just cant return it properly.
Main Function:
int main() {
char * answers;
fp = fopen("data.txt", "r");
if(fp == NULL){
printf("Could not find file.\n");
exit(EXIT_FAILURE);
}
answers = buildAnsArray();
printf("%s", answer[1]); //used as a test to see if i passed the array of strings correctly
fclose(fp);
return 0;
}
in the main function when i try and print a value it just ends up crashing, or printing weird symbols
Assuming this is some flavor of C, you are trying to return a pointer to a variable, answer, which was automatically allocated inside a function, which means it gets automatically deallocated when you exit that function. So either create answer outside of this function and pass it in to be filled, or allocate the space for it explicitly so it can live once the function returns.
As #Scott Hunter pointed out, when you exit the function buildArray, answer goes out of scope, and the memory it occupied is free to be used by another variable. If you want to allocate the memory within buildArray, then you will need to use malloc. A starting point would be:
char *answer;
answer = malloc(x * 10 * sizeof(*answer));
But, using malloc does require you to pay attention to memory and manage it appropriately. This means:
1) Checking that malloc was successful in allocating memory. If it fails it returns Null, so you can add
if(answer == NULL){
//Error Code here
}
2) Freeing the memory when you are done. This should also be done safely. I would suggest the following just before fclose
if(answer != NULL)
{
free(answer);
}
3) Performing your own handling the double indexing yourself. This means that answer[i] becomes either answer + i*10 or &(answer[i*10])
Also, not related to your question, but important to notice:
1) You have a type mismatch between your definition char *answer in main and returning a char** from buildArray. Turning on -Wall and -Wextra on your compiler should warn you about these types of things. And you should try to clean up all of the warnings that are generated. They tend to mean that you either made a subtle mistake, or are using a bad coding practice that you should get out of the habit of, before it creates a major debugging headache.
2) You appear to be using fp as a global variable. You should be trying to avoid global variables as much as possible. There may be times when they are necessary, but you should think about that long and hard before comitting to it.
3) You (correctly) checked that fopen was successful. But, you didn't check that fscanf was successful. You should get in this habit as a failed read from file won't automatically generate a runtime error. You will just get strange results when it uses whatever bits were already in memory for your logic later on.
sample code
#include <stdio.h>
#include <stdlib.h>
#define STRING_SIZE 10
#define S_(x) #x
#define S(x) S_(x)
char (*buildAnsArray(FILE *fp))[STRING_SIZE+1]{
int x, i;
char (*answer)[STRING_SIZE+1];
fscanf(fp, "%d", &x);
answer = malloc(x * sizeof(*answer));
for(i=0; i<x; i++){
fscanf(fp, "%" S(STRING_SIZE) "s", answer[i]);//fscanf(fp, "%10s", answer[i]);
}
return answer;
}
int main(void) {
char (*answers)[STRING_SIZE+1];
FILE *fp = fopen("data.txt", "r");//error proc omit
answers = buildAnsArray(fp);
printf("%s\n", answers[1]);//A3B
fclose(fp);
free(answers);
return 0;
}

C structures, memory alloc and structures

So, the task is to read file and push data to structure. the data file is:
babe 12 red 12
deas 12 blue 12
dsa 12 red 512
bxvx 15 blue 52
reed 18 black 15
while code is something like that
struct shoes {
char name[8];
int size;
char color[8];
int price;
};
//open file
shoes *item=(struct shoes*)malloc(sizeof(struct shoes));
for (i=0; !feof(file); i++) {
item=(struct shoes*)realloc(item,sizeof(struct shoes)+i*sizeof(struct shoes));
fscanf(file,"%s %i %s %i\n",(item+i)->name,(item+i)->size,(item+i)->color,(item+i)->price);
}
but the program crashes every time.
dbg says: No symbol "item" in current context.
where is error?
You code has some bugs:
1) You need a typedef for shoes unless you're compiling with a C++ compiler ... but then you should have tagged this C++.
2) feof doesn't return false until an attempt has actually been made to read beyond the end of file, so your code makes the array of shoes 1 too large.
3) You're passing ints to fscanf instead their addresses.
If compiling as C code, not C++ code, the casts on malloc and realloc aren't necessary and are advised against. And there are other stylistic issues that make you code harder to comprehend than it could be. Try this:
typedef struct {
char name[8];
int size;
char color[8];
int price;
} Shoe;
// [open file]
Shoe* shoes = NULL; // list of Shoes
Shoe shoe; // temp for reading
for (i = 0; fscanf(file,"%s %i %s %i\n", shoe.name, &shoe.size, shoe.color, &shoe.price) == 4; i++)
{
shoes = realloc(shoes, (i+1) * sizeof *shoes);
if (!shoes) ReportOutOfMemoryAndDie();
shoes[i] = shoe;
}
The problem is that you are not passing pointers to the integers you want to read using fscanf, you are passing the integers themselves.
fscanf treats them as pointers. And where do they point? Who knows - the integers were uninitialized, so they could point ANYWHERE. Therefore, CRASH.
Fix thusly:
fscanf(file,"%s %i %s %i\n",
(item+i)->name,
&((item+i)->size),
(item+i)->color,
&((item+i)->price));
Note that you don't need the same for name and color because arrays degenerate to pointers, so you're passing the right thing already.
And please, consider ditching the item+i notation; item[i] is so much clearer and easier to understand when casually reading the code:
fscanf("%s %i %s %i\n",
item[i].name,
&item[i].size,
item[i].color,
&item[i].price);
Are you sure the debugger says that? I'm surprised it even compiled...
You wanted:
struct shoes *item
If you don't proved a typedef of your structure, you have to explicitly say "struct" every time you reference it.
Second note:
item=(struct shoes*)realloc(item...
Don't assign the same pointer from realloc() that you pass into it. If the reallocation fails it will return NULL and that could be killing you. You should make sure you're checking the results of both the initial malloc() and the realloc()
Third point:
You need to be passing the address of the int's to the fscanf().
fscanf(file,"%s %i %s %i\n",(item+i)->name,&((item+i)->size),(item+i)->color,&((item+i)->price));
There are two issues with your code:
1st. The struct:
you could define your struct in two ways,
the way you did:
struct shoe{
char name[8];
int size;
char color[8];
int price;
};
and in this case you should refer to a pointer to it as:
struct shoe *item;
the other (perhaps more convenient?) way using a typedef along with the defenition:
typedef struct {
char name[8];
int size;
char color[8];
int price;
} shoe;
and in this case you should refer to a pointer to it as:
shoe *item;
Therefore the code you posted isn't supposed to compile.
2nd one:
fscanf should be given pointers to integers/chars in the case you showed.
You've correctly passed the char pointer(since you passed the name of a char array which is actually a char pointer to the first element), but you have passed some integers and fscanf needs pointer to integers it is supposed to fill, so your code should be:
fscanf(file,"%s %i %s %i\n",(item+i)->name,&((item+i)->size),(item+i)->color,&((item+i)->price));

Resources