Structures and Strings in C - c

I started learning C and I wrote a short program implementing structures. For now, it only has a structure and a short function that is supposed to fill one of the structures (several are stored in an array). Program gets all the values (currently only for one structure to help me see what's going on) and the problem starts in main, in
printf("%s", tablica[0].nazwa);
Because program stops responding (no errors or warnings before).
If I put:
printf("%d", tablica[0].x);
It will print the value I put as x, so I know there is some problem with string in printf (but I can't figure out why). It's probably easy, but I'm just a beginner.
#include <stdio.h>
#include <string.h>
struct struktura
{
char *nazwa;
double x, y, z;
};
int wczytaj(struct struktura tab[])
{
int i;
for ( i = 0; i<1; i++)
{
printf("Podaj nazwe: ");
scanf("%s", &tab[i].nazwa);
printf("Podaj x: ");
scanf("%i", &tab[i].x);
printf("Podaj y: ");
scanf("%i", &tab[i].y);
printf("Podaj z: ");
scanf("%i", &tab[i].z);
};
return 0;
}
int main(struct struktura* a)
{ int i;
struct struktura tablica[6];
int wyniki[6][6];
wczytaj(tablica);
printf("%s", tablica[0].nazwa);
}
Sorry for some names being in Polish, I can correct that, but I hope it doesn't blur the program).

You are using the wrong format specifiers for double types in
scanf("%i", &tab[i].x);
printf("%d", tablica[0].x);
and others. They should be
scanf("%lf", &tab[i].x);
printf("%f", tablica[0].x);
Also this string input
scanf("%s", &tab[i].nazwa);
should lose the & ampersand like this
scanf("%s", tab[i].nazwa);
but even so nazwa has no memory allocated to it. As suggested in comments you could get going with a fixed array like
struct struktura
{
char nazwa[30];
double x, y, z;
};
You have a very unsual signature for main, which is usually
int main(void)
or
int main(int argc, char *argv[])

Related

My c code won't output anything whatsoever if it has a scanf(); inside of the code

#include<stdio.h>
#include <stdlib.h>
int triArea(x, y) {
int baseTimesHeight = x * y;
int area = baseTimesHeight / 2;
return area;
}
int main() {
int x = 0;
int y = 0;
printf("Enter an integer value for the length: \n");
scanf("%d", &x);
printf("Enter an integer value for the height: \n");
int area1 = triArea(x ,y);
printf("The area of the triangle is: %d\n", area1);
printf("Hello world!\n");
return 0;
}
this is the code that i wrote for a simple calculation (I am VERY new to programming in c and low level languages) however no matter the program if it has a scanf it will not output any other code. Anyone have idea as to why this happens? I'd like both a solution and explanation if possible!:)
You forgot the scanf for y:
...
printf("Enter an integer value for the height: \n");
scanf("%d", &y); // <<<<< you forgot this line
and int triArea(x, y) should be int triArea(int x, int y). Any decent compiler should issue a warning for this.
Bonus: why do you call your variable x, and y? Call them length and height instead. Code readability is very important, and correct naming of variables and functions is very important.

How do you pass 2-dimensional array of character into a function?

So i'm trying to pass
char parent[n][50];
into a function initialize();
And then copy the char x, into the parent [ i ] inside the initialize(); function. Example
x = "Cityname"
and when passed into the initialize();
it would do
strcpy(parent[i], x);
to make the
parent[i] = "Cityname"
void initialize(char *parent, int *ranks, char x, int i){
strcpy(parent[i], x);
ranks[i] = '0';
}
int main(){
int n, i = 1;
char x[20];
printf("Enter how many city are there : "); scanf("%d", &n); fflush(stdin);
char parent[n][20];
int ranks[n];
while(1){
printf("enter city name: "); scanf("%[^\n]", x);
if(i <= n){
initialize(parent[][20], ranks, x, i);
i++;
} else {
printf("The city is at maximum\n");
}
}
}
It tells a warning:
passing argument 1 of 'strcpy' makes pointer from integer without a cast
note: expected 'char *' but argument is of type 'char'
and also in function main
error: expected expression before ']' token
Can anyone explain how to strcpy(parent[i], x) correctly? I can't seem to figure this problem out.
I see several problems with your code. Arrays vs pointers in C can be confusing, so there are a few rules to keep in mind:
char x[n] can be automatically converted by the C compiler to char *x.
char x[10][20] is represented under the hood as a 1D array, and the compiler computes the offsets behind the scenes. For example, if x were a 10 x 20 array, the expression x[1][2] could be compiled as *(x + 22). For this reason, it can cause surprising results to cast a 2D array to a char*, and it is invalid to cast a 2D array to a char**.
With these rules in mind, here is how I would change your code
void initialize(char (*parent)[20], int *ranks, char *x, int i){
strcpy(parent[i], x);
ranks[i] = '0'; // Did you want an automatic conversion from char to int here? Maybe you meant ranks[i] = 0?
}
int main(){
int n, i = 0; // As Craig mentions, i should start at 0.
char x[20];
printf("Enter how many city are there : "); scanf("%d", &n); fflush(stdin);
char parent[n][20];
int ranks[n];
while(1){
printf("enter city name: "); scanf("%19s", x); // scanf will automatically stop at whitespace, and you must include the max length to avoid a buffer overrun.
if(i < n){
initialize(parent, ranks, x, i);
i++;
} else {
printf("The city is at maximum\n");
// Maybe break here, unless you want an infinite loop
}
}
}

Weird results using simple math operations

i have the following struct:
typedef struct number
{
int x;
int y;
int z;
unsigned long int final;
}number;
my code is the following:
number* numbers;
numbers= (number*)malloc(sizeof(number));
scanf("%d %d %d", &numbers->x, &numbers->y, &numbers->z);
printf("input: %d,%d,%d\n",numbers->x, &numbers->y, &numbers->z);
numbers->final=(numbers->x)*4000 + (numbers->y)*50 + (numbers->z);
printf("final: %d",numbers->final);
but the output is wrong. for example here is a run:
12 12 12
input: 12,12,12
final: -28640
i cant figure out the problem. the highest number that number->final can get is 90,000 (i make sure of it as i gives the input)... i seems like there is overlap? please help.
Your problem is the pointer. I am assuming you initialised the struct as follows.
numbers *numbers;
However if you use it in the main where you declare it don't use a pointer. There are also a few errors in your printf call, you are printing the memory address of y and z instead of the value like you did for the x value.
Use something like this.
#include <stdio.h>
typedef struct number
{
int x;
int y;
int z;
unsigned int final;
} number;
int main()
{
number numbers;
scanf("%d %d %d", &numbers.x, &numbers.y, &numbers.z);
printf("input: %d,%d,%d\n",numbers.x, numbers.y, numbers.z);
numbers.final=(numbers.x)*4000 + (numbers.y)*50 + (numbers.z);
printf("final: %d\n",numbers.final);
return 0;
}
Right and if you used malloc it looks like this.
#include <stdio.h>
#include <stdlib.h>
typedef struct number
{
int x;
int y;
int z;
unsigned int final;
} number;
int main()
{
number *numbers = malloc(1 * sizeof(number));
scanf("%d %d %d", &numbers->x, &numbers->y, &numbers->z);
printf("input: %d,%d,%d\n",numbers->x, numbers->y, numbers->z);
numbers->final=(numbers->x)*4000 + (numbers->y)*50 + (numbers->z);
printf("final: %d\n",numbers->final);
free(numbers);
return 0;
}
Running example here
The reason for your wrong answer is because you have kept the datatype as int which has max value of 32767 change it to unsigned long int as your ans calculates to 2400612

Unititialized structure definition [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am having trouble with structure definitions. I understand the syntax but can't use it correctly to make a working program. My assignment is to define a structure type element_t to represent one of the elements of the periodic table. Components should include atomic number, name, symbol, class, weight and a seven element array of integers for the number of electrons in each shell. The following are the components of an element_t structure for sodium.
11 Sodium Na alkali_metal 22.9898 2 8 1 0 0 0 0
Define and test I/O functions scan_element and print_element.
Here is my code... but no worky. I dont understand why the compiler says I haven't initialized element_t. Thanks in advance.
***Ended up with the following code, also added the appropriate loops and & signs although it is not shown below and everything worked fine. I was curious to know how the powerpoint slides in my class used {2 8 1 0 0 0 0} to populate the int array instead of a loop. The book I am using uses the loop method as well but I wanted to try the {} way of doing it. Thanks again.
#include <stdio.h>
#include <string.h>
typedef struct {
int atomic_num;
char* element_name; revised: char element_name[25];
char* element_symbol; revised: element_symbol[2];
char* element_class; revised: char element_class[25];
double atomic_weight;
int electrons[7];
} element_t;
int scan_element(); revised: element_t scan_element();
void print_element(element_t my_element);
int scan_element() {
element_t my_element;
printf("Enter Atomic Number> ");
scanf("%d", my_element.atomic_num);
printf("Enter Element Name> ");
scanf("%s", my_element.element_name);
printf("Enter Element Symbol> ");
scanf("%s", my_element.element_symbol);
printf("Enter Element Class> ");
scanf("%s", my_element.element_class);
printf("Enter Atomic Weight> ");
scanf("%lf", my_element.atomic_weight);
printf("Enter Electons in each shell> ");
scanf("%d", my_element.electrons);
print_element(my_element);
return 0;
}
void print_element(element_t my_element) {
printf("%d %s %s %s %lf %d \n",my_element.atomic_num,my_element.element_name, my_element.element_symbol,my_element.element_class,my_element.atomic_weight,&my_element.electrons);
}
int main()
{
scan_element(); revised: print_element(scan_element());
return 0;
}
I've identified some problems in your code:
1)When reading with scanf non-pointer types(like int or float), use the & operator. Scanf needs a pointer to your variable, not the variable itself.
2)If you declare your strings as dynamic (char*), be sure to use malloc to allocate memory for them. Otherwise declare them statically like char my_string[30].
3)Your scan_element function should return an element_t structure, not an int. Alternatively you could pass a pointer to an existing element_t structure and modify it in your function.
4)You cannot read/print a int array directly using scanf/printf. Every element must be read separately.
5)Your scan_element function shouldn't probably contain print_element :P
If you want to learn more about Console I/O in ANSI C, perhaps this article could be useful.
Here is the corrected code:
include <stdio.h>
#include <string.h>
typedef struct {
int atomic_num;
char element_name[30];
char element_symbol[3];
char element_class[30];
double atomic_weight;
int electrons[7];
} element_t;
element_t scan_element();
void print_element(element_t my_element);
element_t scan_element() {
int i = 0;
element_t my_element;
printf("Enter Atomic Number> ");
scanf("%d", &my_element.atomic_num);
printf("Enter Element Name> ");
scanf("%s", my_element.element_name);
printf("Enter Element Symbol> ");
scanf("%s", my_element.element_symbol);
printf("Enter Element Class> ");
scanf("%s", my_element.element_class);
printf("Enter Atomic Weight> ");
scanf("%lf", &my_element.atomic_weight);
for(i = 0; i<7; i++)
{
printf("Enter Electon - electron nr %d\n",i);
scanf("%d", &my_element.electrons[i]);
}
return my_element;
}
void print_element(element_t my_element) {
int i;
printf("%d %s %s %s %lf\n",
my_element.atomic_num,
my_element.element_name,
my_element.element_symbol,
my_element.element_class,
my_element.atomic_weight);
for(i = 0; i<7; i++)
{
printf("%d",my_element.electrons[i]);
}
puts("\n");
}
int main()
{
element_t val = scan_element();
print_element(val);
return 0;
}

I'm trying to fill an Array with user input, I've already prompted the user now I'm trying to write a fillArray function

#include <stdio.h>
#include <stdlib.h>
#define MAX 25
int readTotalNums();
void fillArray (int nums[], int total);
void sortIt (int nums[], int total);
int findMean (int nums[], int total);
int findMedian (int nums[], int total);
int findMode (int nums[], int total);
void printResults (mean, median, mode);
int goAgain ();
int main()
{
int nums[MAX];
int total;
double mean, median, mode;
do
{
total=readTotalNums();
fillArray(total,nums);
sortIt(nums, total);
mean= findMean (nums,total);
mode=findMode(nums,total);
median=findMedian(nums, total);
printResults(mean,mode, median);
}while(goAgain());
return 0;
}
int readTotalNums()
{
int total;
do
{
printf("How many numbers would you like to enter? (1-25)\n");
scanf("%i",&total);
while(getchar()!='\n');
}while (total<1 || total>MAX);
return total;
}
void fillArray (int nums[], int total)
{
int x;
for (x=0; x<total; x++)
{
printf("enter your numbers\n");
scanf("%i", &nums[x]);
while(getchar()!='\n');
}
}
So I decided to just put up what I have already... because maybe the problem comes before my fillArray function...
I keep getting a "This program has stopped working" message, which, I know you usually get if you don't strip your carriage return. I'm very much a newbie, just trying to make it though my only programming class I have to take for my major, so any help would be appreciated!!
You should pass to scanf a pointer to the location it should store the input, not the value that is already there. scanf("%i", &nums[x]);
The second argument to scanf should be a pointer. Here you are passing an integer. Since this is homework I won't give you the exact code, but that is the problem as far as I can tell.
The scanf function expects pointers, not integers. Didn't you get a compiler warning when you compiled? Try this:
scanf("%i", nums + x);
or equivalently
scanf("%i", &nums[x]);

Resources