Reading from brackets and converting it to an array - c

First of all I must say that I'm quite fresh to programming in C and I just can't overcome one of my problems:
#include <stdio.h>
void main(){
struct huh{
char cos[];
};
huh(abbcabd);
printf("%c",cos[3]);
}
I want the output to be "b" in this case but I don't need to comment that this code doesn't work at all.
I want to enter some text into huh() brackets so then it would be converted to an array or something similar, so I could use the order of entered letters later.
It's important to me that usage of it would look just at it looks now - simply typing anything into those brackets.
So how it should look like?

#include <stdio.h>
#define huh(x) cos = #x
char *cos;
int main(){
struct huh{//unuse type
char dummy;
char cos[];
};
huh(abbcabd);
printf("%c",cos[3]);//print c, array origin 0 in C
return 0;
}

Related

How to convert char pointer to float in C?

I've looked around everywhere and tried pretty much everything suggested and can't get anything to work.
this is my code:
#include <stdio.h>
#include <string.h>
#include <math.h>
int main(){
float a;
char *nums[3];
char str[5];
printf("Please enter a,b,c:");
scanf("%s",str);
int i=0;
char *p;
p = strtok (str,",");
while (p != NULL)
{
nums[i++] = p;
p = strtok (NULL, ",");
}
a=atof(nums[0]);
printf("%s\n",nums[0]);
printf("%f\n",a);
return 0;
}
the math.h is for something later on after I figure this out. So if I entered "1,2,3" into this program, my print statements would show me "1" and then "0.000", this is obviously just there for me to test things out but why the does my value just disappear after trying to convert to a float? I need that value of 1 to do math with later in my program but I can't get that char pointer value no matter what I try, I can only seem to print it, but it screws up as soon as I try to convert it into a type I can use.
Two issues:
You nums and str arrays are too short. nums should have a size of at least 3, and str should be at least 6 ("1,2,3" plus null byte), probably more for larger numbers.
So change those to:
char *nums[3];
char str[20];
Second, you don't #include <stdlib.h>, which contains the declaration of atof. Without a declaration, it is assumed to return an int.
Fix the array sizes, and #include <stdlib.h>, and it should work.

C Array assignment uses brace syntax

I'm working on a display interface with C. Here is the simplified code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define A_BITMAP {1,2,3}
void getA(int **a){
a[0]=(int*)malloc(12);
memcpy(a[0],(int[])A_BITMAP,12);
}
void main(){
int* a;
getA(&a);
printf("%d",a[2]);
free(a);
}
A_BITMAP is one picture's bitmap array, and I cannot modify its code. Here is my question:
Is there any way not using memcpy() to assign to the malloc(ed) area with macro A_BITMAP?
Will (int[])A_BITMAP generate a large local array on stack? The picture's size is about 2M, is it safe to do so?
You can cast it like that. However, casting should be avoided as it's basically telling the compiler you know better than it and disabling any sanity checks it can do. Also, as apparently you don't really know that A_BITMAP is going to be 3 ints, you're opening yourself up to a whole load of pain by hard coding the size.
Moreover, as pointed out by Sunny, it'll likely copy the array onto the stack when written like that (this depends on your compiler, but it's not something I'd like to risk). You really don't want a 2Mb array on the stack, trust me.
A couple of other points:
a isn't an array, it's a pointer so use *a, not a[0], as it's confusing to the reader
you don't return a result from main which means your program
exits with an error.
You might want to consider something like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define A_BITMAP {1,2,3}
void getA(int **a) {
static int data[] = A_BITMAP;
*a = malloc(sizeof(data));
memcpy(*a, data, sizeof(data));
}
int main(){
int* a;
getA(&a);
printf("%d\n", a[2]);
free(a);
return 0;
}
It will create the array on the stack each time the function is called.
It will be better if you declare A_BITMAP as a global array as it will not be allocated on stack.

issue with qsort in c

I have a structure like this :
typedef struct item{
char label[10];
int support;
};
I created an array of such structures like this :
struct item* finstr = (struct item*)malloc(sizeof(struct item)*10);
I filled the array with appropriate values and want to sort the array according to the values of 'support', using the qsort function. But, the array is not getting sorted at all. The output is coming out to be the same as input.
here is the call to the qsort function and the code for the 'comparator' function :
qsort((void*)finstr,(sizeof(finstr)/sizeof(finstr[0])),sizeof(finstr[0]),comparator);
comparator function :
int comparator(const void* i1,const void* i2) {
int l = ((struct item*)i1)->support;
int r = ((struct item*)i2)->support;
return l-r;
}
I do not understand where I am making the mistake. Any help is greatly appreciated.
Thanks in advance.
The expression (sizeof(finstr)/sizeof(finstr[0])) does not give you the number of elements unless finstr is an array. In your case, it evaluates to sizeof(void*)/sizeof(struct item), which is most likely 0.
Replace it with 10.
Excellent advice from #ForhadAhmed:
Its good practice to replace the 10 in malloc(sizeof(struct item)*10) and the size of the array passed to the qsort function with a macro or a variable so that you don't accidentally call qsort with a different sized array than what you intended.
Try building and running the following, to see what answer you get:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char bar[123];
int baz;
} foo;
int main(int argc, char** argv) {
foo *foo_ptr = malloc(sizeof(foo) * 1000);
fprintf(stdout, "%zu\n", sizeof(foo_ptr));
fprintf(stdout, "%zu\n", sizeof(foo_ptr[0]));
free(foo_ptr);
return 0;
}
Depending on architecture, you may notice that sizeof(foo_ptr) is eight bytes — the size of the foo pointer called foo_ptr. Compare this with the value of sizeof(foo_ptr[0]). This should provide a hint at what is wrong.

Pointer initialization. How does it work?

I finished my programming classes in C, and thought I would write some code down. BOOM! I run into so many problems. I guess the C language is so complicated, even a book can't explain how it works entirely.
This is my problem(I am trying to display something using a pointer)
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
char *a;
system("cls");
*a = {"hello"};
printf("%s",a);
getch();
}
*a = {"hello"};
This dereferenced the pointer and assigned something to that memory location. The reason it crashed is because the pointer was uninitialised, ie it did not point at anything (actually it did point at something, but that something was an undefined memory location).
If you had done the following, your program would have worked:
a = "hello";
The type of a is char*. The type of "hello" is also char*.
You don't give value to a pointer to char this way:
*a = {"hello"};
You have to use:
a="hello";
I don't understand very well what you are trying to do. If you only want to print "hello" in your screen, why do you use a pointer to char? What is the getch() for? You use that function this way: http://linux.die.net/man/3/getch Do you intend to read a character?
I would only do:
#include <stdio.h>
main()
{
printf("hello");
}
What are you exactly trying to do?
This is a good reference guide: http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
char *a;// a is pointer which address is store in stack and when u initialize with any string then string is store in code section which cant be change
clrscr();
a = "hello";// this is the way to store the string but if when u assign while declaring as char *a= hello this will accept Remember hello is store in code where as address of pointer a is store in stack section
printf("%s", a);
getch();
}
~
just providing another insight for you..
just now I tried this in Dev-C++ 5.6.3 and it works..
if you assign the value directly when you are declaring it, it works:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
system("cls");
char *a = {"hello"};
printf("%s",a);
getch();
return 0;
}
and one more thing, clrscr is not a standard c function (it didn't work in my test), so how about using cls in stdlib like I did.. hope it's useful..

Function to save data as struct on C

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef struct equipamento {
int codDipositivo;
char nomeEquipamento[40];
char newVar[50];
}Equipamento;
insert(int n, int cat, Equipamento eq[])
{
int codigo;
char newVar[40];
printf("\nNew Var: ");
scanf("%s",&newVar);
eq[n].codDipositivo=newVar;
}
main()
{
Equipamento equipamento[MAX_EQ_DSP];
...a bunch of scanfs
scanf("%d",&n);
scanf("%d",&pr);
insert(n, pr, equipamento);
}
This is a sample of what I have.
on main I have a bunch of scanfs which will update the data showing on the screen but now I want to pass that data into a structure and ask for additional information.
I'm trying to use the updated code but for some reason, instead of 39 chars, it breaks down (returns to the main cycle) after the first char
printf("\nNome do Equipamento: ");
gets(nome);
strcpy(eq[n].nomeEquipamento, nome);
Your problem is this line:
eq[n].codDipositivo=newVar;
In C, you cannot assign arrays, you need to copy them element for element. Remember that C has no string data type, a string is just a NUL-terminated array of char. Luckily there is a function in the C library to help us, strcpy.
strcpy(eq[n].codDipositivo, newVar);
To get the declaration of strcpyyou need to add the following include at the top of your code:
#include <string.h>

Resources