What is wrong ? Functions, loops - loops

I'm just starting my adventure. I'm trying to write a program that sorts an array with a condition (numbers between 1 and 50).
When I want to display the numbers given by the user, the result is only 1. I don't know what is wrong and where to look for the error.
**tytuly.h:** (headliness)
#include <iostream>
class Sortowanie
{
public:
static const int elementy = 5;
int tabela[elementy];
void podajTabele ();
void wyswietlTabele ();
};
**instrukcje.cpp**
#include <iostream>
#include "tytuly.h"
using namespace std;
void Sortowanie::podajTabele()
{
cout<<"Prosze abys podal 5 dowolnych liczb z zakresu miedzy 1-50"<<endl;
for (int i=0; i<elementy; i++)
{
poczatek:
cout<<"Podaj "<<i+1<<" liczbe: "<<endl;
cin>>tabela[i];
if (tabela[i]<=50&&tabela[i]>=1)
{
tabela[i]=true;
}
else
{
cout<<"Niestety podales liczbe spoza dozwolonego przedzialu"<<endl;
goto poczatek;
}
}
void Sortowanie::wyswietlTabele()
{
cout <<"Liczby ktore podales/as to: "<<endl;
for (int i=0; i<elementy; i++)
{
cout<<Sortowanie::tabela[i]<<" ";
}
}
**main.cpp**
#include <iostream>
#include "tytuly.h"
using namespace std;
int main(int argc, char** argv) {
Sortowanie wynik;
wynik.podajTabele();
wynik.wyswietlTabele();
return 0;
}
I can't display user-provided values. Results is "11111"
type here

Related

How to call a function in another C file with a subset of the command-line arguments?

How can I call this convert function using command line and from argument 2 onwards start converting the strings to int and store in an array?
#include <stdio.h>
int main (int argc , char* argv[])
{
int i;
if (argc < 2)
{
printf("Error: Less than two arguments\n");
}
else
{
for(i=0; i<argc; i++)
{
printf("[%d] : %s\n", i , argv[i]);
}
}
return 0;
}
Function in the same directory but in a separate C file:
void convert ( char* parray[] ,int array[] )
{
int i;
printf("The converted array = ");
for (i=0; i< LENGTH; i++)
{
array[i] = atoi(parray[i]);
printf(" %d" , array[i]);
}
printf("\n");
}
You can compile both files into the same executable, e.g like:
gcc -o main main.c convert.c
To use the function in convert.c in main.c, you will have to declare the function before you define the main() function, like this:
#include<stdio.h>
void convert ( char* parray[] ,int array[] );
int main (int argc , char* argv[])
{
// your code ..
//you may now use the convert function inside the main function
convert(param1, param2);
}
Alternatively, you could create a header file for convert.c, called convert.h, like this:
#ifndef CONVERT_H
#define CONVERT_H
void convert ( char* parray[] ,int array[] );
#endif
Then, you could include the headerfile in the main file like this:
#include<stdio.h>
#include "convert.h"
int main (int argc , char* argv[])
{
// use convert here somewhere
convert(param1, param2);
}
Create a module, have the declarations in a separate file, and the implementations in a separate.
functions.h:
#ifndef FUNCTIONS_H /* include guard */
#define FUNCTIONS_H
void convert(char *parray[], int array[], int length);
#endif
functions.c:
#include "functions.h" /* include your header with the declarations */
#include <stdio.h>
#include <stdlib.h>
void convert(char *parray[], int array[], int length)
{
int i;
printf("The converted array = ");
for (i = 0; i < length; i++)
{
array[i] = atoi(parray[i]);
printf(" %d", array[i]);
}
printf("\n");
return;
}
main.c:
#include "functions.h"
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i, *arr = NULL;
if (argc < 2)
{
printf("Error: Less than two arguments\n");
}
else
{
arr = malloc((argc - 1) * sizeof(int)); /* array can be static too */
if (arr == NULL)
{
exit(EXIT_FAILURE);
/* handle error */
}
convert(&argv[1], arr, argc - 1);
free(arr); /* free when you exit */
}
return 0;
}
Compilation:
clang -c functions.c && clang main.c functions.o
OR
clang functions.c main.c
Output:
$ ./a.out 15 20 -90 18 20 20 8 8 8 81
$ The converted array = 15 20 -90 18 20 20 8 8 8 81

I want to sort my struct by alphabetical order, but if i do the sort, my program doesn't give any output

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct kezdo
{
int mennyi;
char betu;
}KEZDO;
int main(int argc, char* argv[])
{
int j;
int i;
int db=0;
int volt=0;
char sajt[22];
FILE* f=fopen(argv[1], "r");
if(f==NULL)
{
fprintf(stderr, "Hiba a fajl megnyitasaban!");
}
int k = 20;
KEZDO t[k];
KEZDO tmp;
for(i=0;i<k;i++)
{
t[i].mennyi = 0;
}
while(fgets(sajt,22,f)!=0)
{
if(sajt[strlen(sajt)-1] == '\n')
{
sajt[strlen(sajt)-1] = '\0';
}
for(i=0;i<k;i++)
{
if(t[i].betu == toupper(sajt[0]))
{
t[i].mennyi++;
volt=1;
}
}
if(volt==0)
{
t[db].betu = toupper(sajt[0]);
t[db].mennyi++;
db++;
}
else
{
volt = 0;
}
}
for(i=0;i<db;i++)
{
printf("%c: %d\n", t[i].betu, t[i].mennyi);
}
return 0;
}
I tried strcmp and stricmp but neither worked. I tried to fully change the struct by sorting the struct properties. When the struct properties are sorted it doesn't work, but it worked before in a non-sorted order. What is preventing output when the struct properties are sorted?
As i can see in your code, you want to sort on char betu. One way to sort structures is via qsort but that'd require comparator function stated below:
int compare(const void *void_a, const void *void_b)
{
const KEZDO *a = void_a;
const KEZDO *b = void_b;
return (a->betu) < (b->betu);
}
//Perform sort like this;
qsort((void *) &t, db, sizeof(KEZDO) , compare );
Moreover, qsort is in #include <stdlib.h>

Segmentation fault with multithreaded array

I am trying to make multithread array sorting program in c. But when I run the program, I get an "segmentation fault" error.
Can someone help?
What should I change? First array should be 300 the other should be 500. We sort sequences separately first. After that merge 2 sorted sequences. I use "gcc -pthreads -0 soru1 soru1.c" and "./soru1" commands.
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#define size 800
int orginal_dizi[size], dizi1[300], dizi2[500], dizi3[size];
int sayi,a=1;
int boyutbul(int *the)
{
int number=-1;
while(the[++number]!='\0'){}
return number;
}
void*runner(void *param)
{
int temp,i,k;
int *bolum = param;
sayi = boyutbul(bolum);
printf("\n----------unsorted %d. array-----------\n\n",a);
for(i=0; i<sayi;i++)
printf("%d\n", bolum[i]);
for(i=0; i<sayi;i++)
{
for(k=0; k<(sayi-i-1);k++)
{
if(bolum[k]>bolum[k+1])
{
temp=bolum[k];
bolum[k]=bolum[k+1];
bolum[k+1]=temp;
}
}
}
printf("\n----------sorted %d. array-----------\n\n",a);
for(i=0; i<sayi;i++)
printf("%d\n", bolum[i]);
a++;
pthread_exit(0);
}
int main()
{
pthread_t tid1,tid2, tid3;
int i=0;
while(i<size)
{
int yenisayi=1+rand()%1500;
int aynimi=0, j=0;
while(j<i)
{
if(orginal_dizi[j]==yenisayi)
{
aynimi=1;
break;
}
j++;
}
if(aynimi)
continue;
orginal_dizi[i]=yenisayi;
i++;
}
for(i=0;i<size;i++)
{
if(i<(300))
{
dizi1[i]=orginal_dizi[i];
}
else
{
dizi2[i-(500)-1]= orginal_dizi[i];
}
}
pthread_create(&tid1,NULL,runner,(void *)dizi1);
pthread_join(tid1,NULL);
pthread_create(&tid2,NULL,runner,(void *)dizi2);
pthread_join(tid2,NULL);
for(i=0; i<size;i++)
{
if(i<300)
{
dizi3[i]=dizi1[i];
}
else
{
dizi3[i]=dizi2[i-500];
}
}
pthread_create(&tid3,NULL,runner,(void *)dizi3);
pthread_join(tid3,NULL);
FILE *fp;
if((fp=fopen("son.txt","w"))== NULL)
printf("Dosya acilamadi.");
for(i=0;i<size;i++)
{
fprintf(fp, "%d\n", dizi3[i]);
}
fclose(fp);
return 0;
}
There is no multithreading in this program: every thread is immediately joined; noting runs in parallel.
The real problem is in boyutbul, which tries to figure out the length of the array by looking for '\0'. The way you initialize the arrays, there is no guarantee that they would have the terminating 0 (in fact, they wouldn't have any zeroes), so the program is doomed to access them beyond the bounds. This is UB.

how we can define and use structure inside function in C?

I am trying to create a structure inside a function and i am trying to use it. But when I am comparing two values from structure I am getting this message :
"C:\Users\hp\Desktop\prgm\cap.c||In function 'fnumber':|
C:\Users\hp\Desktop\prgm\cap.c|
72|error: request for member 'f_value' in something not a structure or union|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
this is my code:-
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
/*
* Complete the function below.
*/
int fnumber(long input1,int input2_size, int* input2)
{
int i, j, k, count[input2_size],temp=0;
int arr_temp[input2_size];
struct smaller{
int position;
int f_value;};
struct smaller list[input2_size];
struct smaller temp1;
memccpy(arr_temp, input2, input2_size,sizeof(int));
for(i=0; i<input2_size;i++)
{
for(j=i+1; j<=input2_size;i++)
{
if(arr_temp[i]>arr_temp[j])
{
temp=arr_temp[i];
arr_temp[i]=arr_temp[j];
arr_temp[j]=temp;
}
}
}
for(i=0; i<input2_size;i++)
{
if(i>1)
count[i]=input2[i];
for(j=0;j<input2[i-1];j++)
{
count[i]+=arr_temp[j];
}
}
/* for(i=0;i<input2_size-1;i++)
{
for(j=i+1;j<input2_size;j++)
{
if(count[i]>count[j])
{
temp=count[i];
count[i]=count[j];
count[j] = temp;
}
}
}*/
for(i=0,j=0;i<input2_size;i++)
{
if(count[i]<=input1)
continue;
else
{
list[j].position=i;
list[j].f_value=count[i];
j++;
}
}
for(i=0;i<input2_size-1;i++)
{
for(j=i+1;j<input2_size;j++)
{
if(list[i].f_value>list[j.f_value])
{
temp1=list[i];
list[i]=list[j];
list[j]=temp1;
}
}
}
return list[0].position;
}
int main() {
int output = 0;
long ip1;
scanf("%ld", &ip1);
int ip2_size = 0;
int ip2_i;
scanf("%d\n", &ip2_size);
int ip2[ip2_size];
for(ip2_i = 0; ip2_i < ip2_size; ip2_i++) {
int ip2_item;
scanf("%d", &ip2_item);
ip2[ip2_i] = ip2_item;
}
output = fnumber(ip1,ip2_size,ip2);
printf("%d\n", output);
return 0;
}
if(list[i].f_value>list[j.f_value])
You misspelled list[j].f_value as list[j.f_value].
Also, memccpy should be memcpy.

Wrong result when copying an array of strings

I have the following code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* user;
char* passwd;
int nr;
void test()
{
int i=0;
for(i=0;i<argc;i++)
printf("Hello %s \n",user);
}
int main(int argc,char*argv[])
{
int i;
nr=argc;
for (i=0; i<argc; i++)
{
user=strdup(argv[i]);
}
test();
return 0;
}
The result is the argv[argc] on all the positions. How can I fix this? I wwant to have that test() outside the loop.
**
EDIT
**
After the ANSWERS here this is my new code, which is not working. Can anyone say why?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* user;
void test(int n)
{
int i=0;
for(i=0;i<n;i++)
printf("%s \n",user[i]);
}
int main(int argc,char*argv[])
{
user = (char*) malloc(argc*sizeof(char));
int i;
for (i=0;i<argc;i++)
{
user[i]=argv[i];
}
test(argc);
return 0;
}
You are assigning to both password and user at each iteration of the for loop. The final values you see are from the last iteration. Also, there is memory leak due to overwriting the pointers from previous strdup calls. In fact, you do not need a loop:
int main(int argc,char*argv[])
{
if(argc == 3) {
user=strdup(argv[1]);
passwd=strdup(argv[2]);
} else {
// error: usage
}
test();
return 0;
}
If you want to have multiple user/password combinations:
char *user[256], *passwd[256];
void test(int n) {
int i;
for(i=0;i<n;i++)
printf("Hello %s \n",user[i]);
}
int main(int argc,char*argv[])
{
int i;
for(i = 0; i < argc && i < 256; i+=2) {
user[i]=strdup(argv[i]);
passwd[i]=strdup(argv[i+1]);
}
test(argc);
return 0;
}
Because you overwrite the pointers user and passwd in every iteration. Hence, you'll only see the last string.
If you can tell your aim of the program, a better answer can be provided. Because I am not sure whether you want to read one user and passwd Or an array of users and passwds.
After you edit, I see you want to read an array of strings:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char** user;
// or char *user[100]; /* If you want a fix length array of pointers. Now, you dont have to malloc. /*
char* passwd;
int nr;
void test(int argc)
{
int i=0;
for(i=0;i<argc;i++)
printf("Hello %s \n",user[i]);
}
int main(int argc,char*argv[])
{
int i;
nr=argc;
user = malloc(argc*sizeof(char*));
for (i=0; i<argc; i++)
{
user[i]=strdup(argv[i]);
}
test(argc);
return 0;
}
Of course; in test() you don't use i other than a loop variable and in main() you keep overwriting the previous value of user and passwd. In effect, what you do is:
user = strdup(argv[0]); /* Note: argv[0] is the program name. */
passwd = strdup(argv[0]);
user = strdup(argv[1]);
passwd = strdup(argv[1]);
user = strdup(argv[2]);
passwd = strdup(argv[2]);
user = strdup(argv[3]);
passwd = strdup(argv[3]);
printf("%s %s \n", user, passwd);
With this information, can you fix your program?
$ cat trash.c
#include <stdio.h>
#include <string.h>
void test(FILE* stream, char* usr, char* pass) {
fprintf( stream, "%s#%s\n", usr, pass);
}
int main(int argc, char** argv) {
int i = 1;
if (argc % 2) {
while(argv[i]) {
test(stdout, argv[i], argv[i + 1]);
i += 2;
}
}
return 0;
}
$ clang trash.c
$ ./a.out user1 pass1 user2 pass2
user1#pass1
user2#pass2
$
also if you call strdup() don't forget to free memory, because strdup called malloc().

Resources