Printf not showing and return value 3221225477 - c

New to C and programming in general, so I am having kind of a tough time with structs when combined with arrays and pointers. I'm trying to create a struct with attempts, then create an array pointer (towards the struct) repeating it 10 times. Then find the average for every struct and print it.
Everything seems to work normally providing a return value of 0 until the loop.
#include <stdio.h>
#include <stdlib.h>
typedef struct Tries {
float attempts1;
float attempts2;
float attempts3;
float aver;
}Try;
int main(int argc, char *argv[]) {
int i,size=10,at1,at2,at3;
Try** arrayofTries= malloc (sizeof(Try)*size);
for (i=0;i<size;i++){
arrayofTries[i]->attempts1= rand () %(900 - 700)+700;
arrayofTries[i]->attempts2= rand () %(900 - 700)+700;
arrayofTries[i]->attempts3= rand () %(900 - 700)+700;
at1= arrayofTries[i]->attempts1;
at2= arrayofTries[i]->attempts2;
at3=arrayofTries[i]->attempts3;
arrayofTries[i]->aver = (at1+at2+at3)/3;
printf ("The average of %d person is%f",i,arrayofTries[i]->aver);
}
return 0;
}

arrayofTries should be of type Try * not Try **
Try *arrayofTries = malloc (sizeof(Try) * size);
So all your -> should be simple dots ..

You are allocating a pointer to pointer to Try but not allocating the direct pointer to the elements themselves. It looks like your intent is to declare a 1D array, not a 2D array, so what you should do is change the type of arrayofTries from Try ** to Try *.
Also, when you're done using memory allocated with malloc, free it:
free(arrayofTries);
arrayofTries = NULL;

Related

Adding pointers to an array of pointers

I'm trying to make a program that for a given int value keeps the amount of dividers:
int amount_of_dividers and a list of those dividers: int* dividers
This is the code:
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int value;
int amount;
int* dividers;
} Divide;
int main(){
Divide ** tt;
read_dividers(tt,5);
}
/* the functions "amount_of_dividers(int g)" and "dividers_of(int g, int amount)"
used in void read_divider are working properly, they are not needed for this question */
void read_divider(Divide *g){
scanf("%d",&(g->value));
g->amount = amount_of_dividers(g->value);
g->dividers = dividers_of(g->value,g->amount);
}
/* assuming that read_divider works, what causes read_dividerS to crash? */
void read_dividers(Divide ** t, int amount){
int i = 0;
t = malloc(amount*sizeof(Divide*));
for(i = 0;i<amount;i++){
read_divider(t[i]);
}
}
Read_dividers uses an array of pointers **t where i'm trying to fill each element of this array with a pointer to a Divide g variable.
EDIT: input in this case in main() : "read_dividers(tt,5)" means the user gives 5 int's, which get converted to 5 Divide structs.
What happens instead is the program crashes after I give in the second int
If any more information is missing, don't hesitate to ask!
You are passing an uninitialized t[i] to read_divider. t is supposed to be pointer to pointer to Divide, not pointer to Divide, you may have just got lucky on your first pass, but I suspect it failed on the very first call.

Change Array without returning it [C]

I just have a basic question concerning arrays in functions.
I am trying to change an array in a function without returning it.
I know how to do this for integers or doubles but i didn't know how to do this for arrays. So i experimented a little bit and now I am confused.
I have 2 variations of my code which i thought should do the same thing , but they don't. I pass the array b to the function Test. In the function I try to fill the array with the values 0, 1 ,2
#include <stdlib.h>
#include <stdio.h>
void Test(int * vector){
vector = malloc(3*sizeof(int));
int i;
for(i=0;i<3;i++){
*(vector+i)=i;
}
}
int main(){
int b[3];
Test(b);
printf("%i\n",b[0]);
printf("%i\n",b[1]);
printf("%i\n",b[2]);
return EXIT_SUCCESS;
}
This Version doesnt work, i don't get the expected result 0,1,2
This Code on the other hand does seem to work:
#include <stdlib.h>
#include <stdio.h>
void Test(int * vector){
int * b = malloc(3*sizeof(int));
int i;
for(i=0;i<3;i++){
*(b+i)=i;
*(vector+i) = *(b+i);
}
}
int main(){
int b[3];
Test(b);
printf("%i, ",b[0]);
printf("%i, ",b[1]);
printf("%i ",b[2]);
return EXIT_SUCCESS;
}
Can somebody explain to me why only the second one works?
Best Regards,
Rob
When you pass an array to a function, it decays into a pointer to the first element. That's what the function sees. But then you take the function parameter vector and overwrite it with dynamically allocated memory. Then you don't have access to the array you passed in. Additionally, you have a memory leak because you didn't free the allocated memory.
In the case of the second function you don't modify vector, so when you dereference the pointer you're changing b in main.
Also, instead of this:
*(vector+i)
Use this:
vector[i]
It's much clearer to the reader what it means.
test doesn't need to call malloc(). When you use an array as a function argument, it passes a pointer to the array. So you can simply write into vector[i] and it will modify the caller's array.
void Test(int * vector){
int i;
for(i=0;i<3;i++){
*(vector+i)=i;
}
}

C: 2d char pointer in a struct

I want to write and print some strings in a 2d array in a struct. The struct is called Router and it is in a header file, the 2d array is defined in that struct and it's called **addTab. When I try to print one line of the array using the function viewTable the program stopped working... why?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "router.h"
#define N 8
#define M 3
#define sizeMess 5
Router *createRouter(){
Router *NewRouter=(Router*)malloc(sizeof(Router));
int i;
NewRouter->addTab=(char **) malloc(N*sizeof(char *));
for(i=0;i<N;i++)
NewRouter->addTab[i]=(char *) malloc(M*sizeof(char));
return NewRouter;
}
void viewTable(Router *r, int a){
int i,j;
for(i=0;i<N;i++){
for(j=0;j<M;j++){
printf("raw\t col\t address\t value\t\n");
printf("%d\t %d\t",i,j);
printf("%p\t",&r->addTab[i][j]);
printf("%s\t\n",r->addTab[i][j]);
}
}
}
void updateTable(Router *r, int conn, char *addr1, char *addr2){
r->addTab[conn][1]=addr1;
r->addTab[conn][2]=addr2;
}
First off: Don't cast the result of malloc.
Assuming that you want to store char* pointers in your 2D array (as the title of your question says), you will need to define it as char *** in your Router structure, like this:
typedef struct router {
char ***addTab;
} Router;
Next, you will need to change your createRouter function, so that it can store an array of char* pointers, instead of a single byte for each element, like so:
Router *createRouter(){
Router *NewRouter=malloc(sizeof(Router));
int i;
NewRouter->addTab=malloc(N*sizeof(char **));
for (i=0;i<N;i++)
NewRouter->addTab[i]=malloc(M*sizeof(char *));
return NewRouter;
}
I'm not sure how you call your updateTable function, but unless you actually fill up the entire array with char* pointers, your viewTable function will also invoke Undefined Behavior, because the printf statements will attempt to access uninitialized data. You could avoid this by using calloc instead of malloc when allocating the 2D array (or explicitly memset it), and then adding NULL checks in your viewTable function.
Finally, if you're calling updateTable with char* pointers that are not string literals or they have not been allocated on the heap, you might have further issues...
Your updateTable() doesn't work as you'd expect. You allocated memory in r->addTab[i][j] and, afterwards, assign a pointer to it (r->addTab[conn][1]=addr1). On access in viewTable, the program tries to read the memory at addr1, but most likely won't be able to read it, thus crashes.
Use a function to copy a given string to r->addTab, e.g. like so:
void router_tab_printf(Router *r, const int conn, const int i, const char *value) {
sprintf(r->addTab[conn][i], "%s", value);
}
This assumes that r->addTab[conn][i] is large enough to hold value.
you need to change your updateTable
void updateTable(Router *r, int conn, char *addr1, char *addr2){
strcpy(r->addTab[conn], addr1);
strcpy(r->addTab[conn+1 /*or something*/], addr2);
}

C: dynamic declare array size

I have the following declaration inside a function
int f[20000]
I want the number 20000 to be dynamic, How can i declare such array in code?
To be more specific, I have the following code to calculate PI.
#include <stdlib.h>
#include <stdio.h>
#define BITS 2000
int a=10000,b,c=BITS*7/2,d,e,f[BITS*7/2+1],g;
int main()
{
for(;b-c;)
f[b++]=a/5;
for(;d=0,g=c*2;c-=14,printf("%.4d",e+d/a),e=d%a)
for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b);
//getchar();
return 0;
}
I changed to
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
//
// .... omit some lines here
// read bits from user input at runtime
// say precision = 200
//
int a=10000,b,c=precision *7/2,d,e,f[precision *7/2+1],g;
for(;b-c;)
f[b++]=a/5;
for(;d=0,g=c*2;c-=14,printf("%.4d",e+d/a),e=d%a)
for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b);
//getchar();
return 0;
}
It doesn't work, I googled then changed to
int a=10000,b,c=precision *7/2,d,e,g;
int *f=calloc(precision *7/2+1, sizeof(int));
It still doesn't work, I mean the program doesn't crash, the value it calculated is not correct. What's wrong? Thank you.
There are two ways to achieve what you want.
use dynamic memory allocation. malloc()/calloc()
use variable-length array (in c99)
That said, as pointed out by #user3386109, the problem in your second code snippet is use of uninitiated variable b. You may want to explicitly initialize the local variables before using their value.
You get a dynamically sized array by allocating on the heap using malloc (or calloc).
Replace
int f[20000];
with
int *f = (int *) malloc(20000 * sizeof(int) );
The difference is that global variables are guaranteed to be initialized to 0 (unless initialized to some other value). But local variables are garbage unless you initialize them. So the problem is that variable b starts out as garbage in the second snippet.
In the original code:
int a=10000,b;
int main(void)
{
}
a will start with the value 10000 because you initialized it, and b will start as 0 because it is an uninitialized global variable.
In the changed code:
int main(void)
{
int a=10000,b;
}
a will start with the value 10000 because you initialized it, and b will start as some random value (e.g. 0x5315fe) because it is an uninitialized local variable.
Replace int f[2000]
with
int *f = new int[2000];
then use the array as f[0] = 1, f[1] = 2 etc...
when finished free up memory with delete [] f;
the array size could be allocated by a variable
eg.
int x = 2000;
f = new int[x];

Allocating memory for array in struct (in C)

I need to define a type-struct in C that contains an array to be malloc'd as:
#include <stdio.h>
#include <stdlib.h>
typedef struct mine
{
int N;
double *A;
} mine;
int main(int argc, char** argv)
{
int i;
mine *m=malloc(sizeof(mine));
printf("sizeof(mine)=%d\n",sizeof(mine));
scanf("Enter array size: %d",&(m->N));
m->A=malloc((m->N)*sizeof(double));
for(i=0; i < m->N; i++)
m->A[i]=i+0.23;
printf("First array element: %lf",m->A[0]);
return (EXIT_SUCCESS);
}
The program compiles and runs, and the integer assignment seems to work fine. The array is not working as it should, however.
Any suggestions? I would like m to remain a pointer (to pass to functions etc.).
Thanks.
This is your problem:
scanf("Enter array size: %d",&(m->N));
It should be two separate steps:
printf("Enter array size: ");
scanf("%d",&(m->N));
(and for debugging checking:)
printf("The size entered appears to be %d\n", m->N);
That way, you know if you got the value you intended to get!
If #abelenky answered your question fine, but I was always told to cast the results of malloc from the void * it returns into whatever you are actually working with.
mine *m = (mine *)malloc(sizeof(mine));

Resources