Printing out dynamically allocated memory in C - c

I'm a total beginner in programming and got an assignment about dynamically allocated memory. One of the expected outputs was a printf statement where all the entered inputs(integers) are printed in a single line, in a row. I have managed to printf in a for-loop, but thats not enought. How do I printf them in a single code-line? Here's the code:
int main()
{
int how_many_integers, count, entered_integers, i, *pSize;
printf("\nHow many integers are you going to type?\n");
scanf("%i", &how_many_integers);
getchar();
// Allocates memory for the integers.
pSize = malloc (how_many_integers * sizeof(int));
// Checks if the integer is 0, and/or reads in all the integers.
if (how_many_integers == 0)
{
printf("No numbers were given.\n");
exit(0);
}
printf("Please enter your integers.\n");
for (int i = 0; i < how_many_integers; i++)
{
scanf("%i", &entered_integers);
count++;
pSize[i] = entered_integers;
}
for (int i = 0; i < how_many_integers; i++)
{
printf("Number: %i\n", *(pSize+i));
}
free(pSize);
printf("Count: %i", count);
return 0;
}

Try this:
printf("Numbers:");
for (int i = 0; i < how_many_integers; i++)
{
printf(" %i", *(pSize+i)); // No \n
}
printf("\n"); // if you want a new line at the end
This should result in an output like
Numbers: 1 2 3 4 5
And as others mentioned, your count variable is never initialized. Initialize it to 0.

Related

How does a program run in c?

I'm just learning programming with c.
I wrote a program in c that had a bug in the body of the while loop
I did not put {}.
The program is as follows, but the question that came to me later is how to run the program in c? Why does error 2 not print while it is before the start of the while loop? If the c language is a compiler, why is it that the error of the whole program is not specified first, and up to line 15 the program is executed without any problems?
int main()
{
int n ,k;
float d ;
printf("please write your arithmetic sequence sentences ");
scanf("%d",&n);
printf("\n");
printf("please write your common differences");
scanf("%d",&k);
printf("\n");
printf("please write your initial element ");
scanf("%f",&d);
printf("error 1");
printf("\n");
printf("error 2");
printf("number \t sum");
printf("erorr 3");
int i = 0;
int j = 0;
int sum = 0;
while (i < n)
j = d + i*k;
sum += j;
printf("%d\t%d",j,sum);
i++;
return 0;
}
Firstly, the program enters an infinite loop:
while (i < n)
j = d + i*k;
Since the values of i and n do not change, the condition never becomes false.
Secondly, the printing sequence:
printf("error 2");
printf("number \t sum");
printf("erorr 3");
does not display a line break at the end. The output is buffered (stored internally) waiting for the line break to be printed, which, naturally, never happens. Add \n at the end of "erorr 3" to see the difference.
#include <stdio.h>
int main()
{
int n ,k;
int i = 0;
int j = 0;
int sum = 0;
float d ;
// If the given values are not an integer, it wouldn't continue the sequence and end as an "error"
printf("please write your arithmetic sequence sentences ");
if(scanf("%d",&n)){
printf("please write your common differences");
if(scanf("%d",&k)){
printf("please write your initial element ");
if(scanf("%f",&d)){
printf("Number \tSum\n");
} else {
printf("error");
}
} else{
printf("error");
}
} else{
printf("error");
}
// This is where the values get solved
// You also forgot to add {} in your while statement
while (i < n){
j = d + i*k;
sum += j;
printf("%d\t%d",j,sum);
i++;
}
return 0;
}

segmentation fault (core dumped) gcc ubuntu

I was trying to make a simple function to make a group of number that user enters them, using pointer of pointer but i keep getting this error and its hard to tell where the problem is, if there any other option to use something else that tells me where the problem is instead of this weird error.
#include <stdio.h>
void BuildGroub(int** group,int* count){
int i=0;
int j;
printf("Enter the size of the group \n");
scanf("%d", &*count);
while(*count != 0){
printf("Enter the %d number of the group:\n", i);
j=0;
scanf("%d", &**(group+i));
while(**(group+i)!=**(group+j)){
j++;
}
if(j==i){
i++;
count--;
} else{
printf("you have already entered this number please try again: \n");
}
}
}
int main(){
int count;
int group[100];
int *groupptr = &group;
BuildGroub(&groupptr,&count);
for(int i=0;i<count;i++){
printf("%d, ", group[i]);
}
return 0;
}
With this question, you do not need to use double pointer. If you want to learn how to use the double pointer, you can google then there are a ton of examples for you, for example, Double Pointer (Pointer to Pointer) in C.
In BuildGroub you decrease the count pointer
if(j==i){
i++;
count--;
}
, but in the condition of while loop, you compare the value that count pointer points to. it seems strange.
while(*count != 0)
Even if you change count-- to (*count)--, it will decrease the number of elements that you enter to 0 when you get out of the while loop, then in main function:
for(int i=0;i<count;i++){} // count is equal to 0 after calling BuildGroub function if you use (*count--) in while loop.
You should use a temp value for while loop function, for example:
int size = *count;
while(size != 0){
...
if (i == j) {
i++;
size--;
}
}
You should use, for example, group[i] instead of *(group+i). It will be easier to read your code.
The code complete:
#include <stdio.h>
void BuildGroub(int* group,int* count){
int i=0;
int j;
printf("Enter the size of the group \n");
scanf("%d", count);
int size = *count;
while(size != 0){
printf("Enter the %d_th number of the group:\n", i);
j=0;
scanf("%d", &group[i]);
while(group[i] != group[j]) {
j++;
}
if(j==i){
i++;
size--;
} else{
printf("you have already entered this number please try again: \n");
}
}
}
int main(){
int count;
int group[100];
int *groupptr = group;
BuildGroub(groupptr,&count);
for(int i=0;i<count;i++){
printf("%d, ", group[i]);
}
return 0;
}
The test:
./test
Enter the size of the group
5
Enter the 0_th number of the group:
1
Enter the 1_th number of the group:
2
Enter the 2_th number of the group:
2
you have already entered this number please try again:
Enter the 2_th number of the group:
3
Enter the 3_th number of the group:
3
you have already entered this number please try again:
Enter the 3_th number of the group:
4
Enter the 4_th number of the group:
5
1, 2, 3, 4, 5,
If you want to use a double pointer, you need to change your function like this:
void BuildGroub(int** group, int* count) {
int i = 0;
int j;
printf("Enter the size of the group \n");
scanf("%d", &*count); //I think this is redundant but works.
while (*count != 0) {
printf("Enter the %d number of the group:\n", i);
j = 0;
scanf("%d", (*group + i)); //The content of group + i
while ( *( *group + i) != *(*group + j)) { //the content of the content
j++;
}
if (j == i) {
i++;
(*count)--; //The content decrement
} else {
printf("you have already entered this number please try again: \n");
}
}
}
But you have a big problem in main and it is because you are using the parameter count to decrement until zero inside the function. So when the function finish, count value is zero and you don't print anything... You need to change this, using a internal variable to make the count, and finaly, setting the parameter to be using in main.

Sorting inputted integers into odd and even arrays

I'm a beginner to C, and am trying to sort user inputted numbers into odd and even arrays. I don't understand why my code isn't working.
Cheers.
This is my code, I don't understand my mistake.
int x[]= {};
int i=0;
int d=0;
int j=0;
int even[12]={};
int odd[12]={};
printf("Enter amount of numbers: "); // asking user for amount of numbers
scanf("%d", &d);
for (j=0; j<d; j++){
printf("Enter number %d: ", i+1); // scanning input into 'x' array
scanf("%d", x[i]);
}
printf("Even numbers: ");
for (i=0; i<d; i++) {
if (x[i] % 2 == 0) { // sorting into even array
even[i]=x[i];
printf("%d \n", even[i]);
}
}
printf("\n Odd numbers: ");
for (i=0; i<d;i++){
if (x[i] % 2 != 0) { // sorting into odd array
odd[i]=x[i];
printf("%d \n", odd[i]);
}
}
This error message keeps coming up:
$ ./main
Enter amount of numbers: 4
Enter number 1: 6
Segmentation fault (core dumped)
int x[]= {}; doesn't work because it would hold no elements. But initializing it with {} doesn't work in C anyway, do this instead:
int x[24] = {0}; // first element explicitely set to 0, the rest default-initialized to 0
You also need to put {0} for even and odd. If it's compiling for you with {} then it's possible that you're compiling it as a C++ program, or perhaps your compiler just tolerates it anyway (but it won't work on every C compiler).
scanf needs the address of the int, so instead of scanf("%d", x[i]); you need scanf("%d", &x[i]);. But i is the wrong iterator for this for (j = 0; j < d; j++) loop. Instead do this:
for (j = 0; j < d; j++) {
printf("Enter number %d: ", j + 1); // scanning input into 'x' array
scanf("%d", &x[j]);
}
Also note that the way you're doing this, half the array will be left at 0. So for instance if I imputted the values 1 through 6, then odd contains the values 1 0 3 0 5 0.

Creating a int * with malloc and then use realloc when full

In a function I created am I trying to allocate a int array dynamically to store some index values.
First I create the int * with the malloc function and then let the loop store som values in it and increament the pointer each time.
The problem I run in to starts when I try to use the realloc to increase the memory allocation.
When I do this VS tells me it runs in to undefined behaviour and breaks the program.
The code looks like this
void showAvailable(CabinHolder *holder, Booking *booking)
{
system("cls");
printf("Choose cabin number \n");
printf("Start week: &d \t End week: %d", booking->rentPeriod[0], booking->rentPeriod[1]);
printf("------------------------------------------\n");
int memory = 5;
int *indexOfCabin = (int *)malloc(sizeof(int)*memory);
int counter = 1;
for (int i = 0; i < CABINS; i++)
{
if (counter == memory)
{
memory *= 2;
int *expanded = realloc(indexOfCabin, (memory * sizeof(int)));
indexOfCabin = expanded;
expanded = NULL;
}
if (booking->cabin->typeOfCabin == holder->arrofCabin[i].typeOfCabin)
{
printf("%d. \t Cabin with number %d \t cost: %d per week\n", counter, holder->arrofCabin[i].nr, holder->arrofCabin[i].cost);
counter++;
indexOfCabin = &i;
indexOfCabin++;
}
}
free(indexOfCabin);
system("pause");
}
When I debugg in VS i also se that my pointer indexOfCabin seems to be undefined inside the if statement, which I don't understand.
What have I missed here?
Okay after some help in the comment section I solved the problem with this edited code segment.
void showAvailable(CabinHolder *holder, Booking *booking)
{
system("cls");
printf("Choose cabin number \n");
printf("Start week: %d \t End week: %d\n", booking->rentPeriod[0], booking->rentPeriod[1]);
printf("------------------------------------------\n");
int memory = 5;
int *indexOfCabin = malloc(sizeof(int)*memory);
int counter = 1;
int items = 0;
int choice = 0;
for (int i = 0; i < CABINS; i++)
{
if (counter-1 == memory)
{
memory *= 2;
indexOfCabin = realloc(indexOfCabin, (memory * sizeof(int)));
}
if (booking->cabin->typeOfCabin == holder->arrofCabin[i].typeOfCabin)
{
printf("%d. \t Cabin with number %d \t cost: %d per week\n", counter, holder->arrofCabin[i].nr, holder->arrofCabin[i].cost);
counter++;
indexOfCabin[items++] = i;
}
}
free(indexOfCabin);
system("pause");
}
First: Problem was indexOfCabin = &i throws away the memory you allocated, and puts the address of i into the pointer instead of what I wanted to do. Now we store the index in i in the pointer.
Second: indexOfCabin can be used like an array, e.g. indexOfCabin[counter] = i;. But counter needs to start at 0, and should be incremented after being used. And indexOfCabin should not be incremented

Segmentation fault in my program

My sorting program results in a "segmentation fault 11":
#include <stdio.h>
int main()
{
// Asking user for number of inputs in an array
int n;
do {
printf ("enter the number of intigers you want to sort\n");
scanf("%d",&n);
}while (n<=1);
int sort [n];
printf ("please enter %d numbers\n",n);
for (int i=0; i<n; i++) {
scanf("%d",&sort[i]);
}
printf("you entered\n ");
for (int i=0; i<n; i++) {
printf(" %d ",sort[i]);
}
printf("\n");
int k,c,i,x;
for (i=0;i<n;i++) {
if (sort[i]<sort[i-1]){
k=i-2;
while (sort[k]>sort[i]){
k--;
}
k++;
x =sort[i];
c=i;
for (c=i;c>k;c++){
sort[c-1]=sort[c];
}
sort[k]=x;
}
}
printf ("Sorted numbers :-\n");
for (int i=0; i<n; i++) {
printf ("%d ",sort[i]);
}
printf ("\n");
return 0;
}
Now I have looked up the internet and found that it is caused because a variable has value that exceeds the system's memory limit. But cannot understand that concept.
for (i=0;i<n;i++)
{
if (sort[i]<sort[i-1])
You are accessing array out of its bounds.Maybe you want to start your loop from 1.Also
k=i-2;
while (sort[k]>sort[i])
will access index beyond 0 for example if i is 0 or 1 or 2
k = i - 2; looks unstable for low values of i.
sort[i - 1] is undefined when i is zero.
The thing causes the behaviour of sort[k] to be undefined.
Moral of the story: check all the array indexes before attempting to retrieve an array element. Your debugger will help you here.
In addition to all said before:
c=i;
for (c=i;c>k;c++){
sort[c-1]=sort[c];
}
sort[k]=x;
i can be 0 -> c can be 0 -> sort[c-1] would also result in accessing array out of bounds.
There is no need to initialize c=i twice. It is enough to do it in the loop-declaration

Resources