I have 2 language codes coming in the stream. I'm storing this in a 3 byte char array(unsigned char a[3]). I wanted to compare it with another value stored in a pointer(unsigned char *c).The array a[3] is stored inside a structure(struct s[2]) to get the multiple datas - Is this correct as i'm little confused as array - const pointer cannot be made to point to another location as it is already pointing to a location. But including the array inside a structure and making the zeorth element of the structures array to point to one location and the 1 st element of the structures array is possible. Is the understanding i have is correct.
I wanted to store the 2 array values.So I have declared a structure inside which i have declared the 3 byte char array.Is this way of doing is correct. Is there alternate way to do it.
EDITED:
#include<stdio.h>
int main(){
int i,flag=0,count=0;
struct n{
unsigned char b[3];
};
unsigned char *d=NULL;
struct s{
unsigned char *a;
};
struct s m[2];
struct n w[2];
// memcpy(w[0].b,"eng",sizeof("eng"));
// memcpy(w[1].b,"fre",sizeof("fre"));
strcpy(w[0].b,"eng");
strcpy(w[1].b,"fre");
d = w[1].b; // current lang
m[0].a = w[0].b; // storing the 2 lang in a pointer inside a structure
m[1].a = w[1].b;
i=0;
printf("\nm[0].a:%s\n",m[0].a);
printf("\nm[1].a:%s\n",m[1].a);
printf("\nw[0].b:%s\n",w[0].b);
printf("\nw[1].b:%s\n",w[1].b);
while((m[i].a) && d){ // And comparing
if(m[i].a++ != d++){
flag =1; //if strings are unequal break;
break;
}
i++;
}
if(flag){
printf("Not equal\n");
}
else{
printf("\nEqual\n");
flag =0;
}
return 0;
}
o/p:
m[0].a:engfre
m[1].a:fre
w[0].b:engfre
w[1].b:fre
Not equal
But there s an mistake it shows un equal . Is this way of storing the arrays in a pointer inside a strucutre is correct method. or is there any other way to do this.
EDIT:
I wanted to compare the 2 strings. The 2 strings are equal but i'm getting it as unequal.
Is the pointer a need to be stored in a structure to store the 2 arrays or is there another way of dong this.
#include <stdio.h>
#include <string.h>
int main(){
int i,flag=0,count=0;
struct n{
unsigned char b[4];
};
struct s{
unsigned char *a;
};
unsigned char *d=NULL;
struct s m[2];
struct n w[2];
strcpy(w[0].b,"eng");
strcpy(w[1].b,"fre");
d = w[1].b; // current lang
m[0].a = w[0].b; // storing the 2 lang in a pointer inside a structure
m[1].a = w[1].b;
for (i =0; i <= 1; i++) {
printf("\nm[%d].a: %s d: %s\n", i, m[i].a, d);
if (strcmp(m[i].a, d) != 0) {
printf("Not equal\n");
}
else{
printf("\nEqual\n");
}
}
return 0;
}
Related
Anyone know how to return 3 char values from a function to the main part? The three chars have to be input by the user and made into a pyramid. I have been told to use pointers but don't understand how to do it and keep getting errors. These 3 characters then have to be used in the main function to make a pyramid shape.
To expand on my comment, there are basically two ways I would recommend solving this problem, of which the first comes in two variants (depending on use-case and requirements).
Pass an array as argument to the function, and have it filled in. This comes with two variants depending on what is needed:
Just use an ordinary array
void doSomething(char *array)
{
array[0] = 'A';
array[1] = 'B';
array[2] = 'C';
}
Call like
char array[3];
doSomething(array);
printf("First character is '%c'\n", array[0]);
The second variant is basically the same as above, but treats the array as a (null-terminated) string:
void doSomething(char *array)
{
strcpy(array, "ABC");
}
Call like
char array[4]; // One extra for terminator
doSomething(array);
printf("String is '%s'\n", array);
The second way to return multiple values is through the use of structures:
struct Data
{
char a;
char b;
char c;
};
struct Data doSomething(void)
{
struct Data data;
data.a = 'A';
data.b = 'B';
data.c = 'C';
// or struct Data data = { 'A', 'B', 'C' };
return data;
}
Call like
struct Data data = doSomething();
printf("First character is '%c'\n", data.a);
I write an example of pointers, I hope it's useful:
main(){
int a,b,c;
doSomething(&a,&b,&c);
}
void doSomething(int *x, int *y, int *z){
//example
*x = 5;
*y = 7;
*z = 10;
}
I have a program which creates an array or struct and go through it for processing. Initially it initialize the array with the defined nyumber of elements. Then for some number of element in array, the name is assigned.
I pretend the code that is equal to my scenario which is tested in codebloc and get the similar error. The problem is described in comments.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _car {
char *name;
int year;
} Car;
char *getCarName(char *name, int var);
void processCar();
void printCars(Car car[]);
int INCREMENT = 10;
int main(void)
{
processCar();
return 0;
}
void processCar()
{
// create car array with amount of INCREMENT
Car CAR_ARRAY[INCREMENT];
int a=0;
// This function assign name for Car amount 10 less than INCREMENT
while (a<INCREMENT - 2) {
char *carName;
carName = getCarName(&carName, a);
CAR_ARRAY[a].name = malloc(strlen(carName) + 1);
strcpy(CAR_ARRAY[a].name, carName);
a++;
}
printCars(CAR_ARRAY);
}
void printCars(Car car[])
{
printf("IN Car \n");
int a = 0;
// when try to call name for car amount equals to INCREMENT program terminates.
while(a<INCREMENT) {
if (car[a].name != NULL) // checking if NULL
printf("Car Name : %d -> %s\n", a, car[a].name);
a++;
}
}
char *getCarName(char *name, int var)
{
name = "Toyota";
return name;
}
What is the right way to check the struct value on struct array whether it can be called?
EDIT
I created a hack to do this as follows.
// added these right after creating array
for (a = 0; a < INCREMENT; a++)
CAR_ARRAY[a].name = NULL;
I dont know if it is a standard way or not. pls advice.
You are checking for NULL before printing, which is a good idea, but it doesn't help you here, because your last two cars are uninitialised and likely contain garbage: The name pointer is not NULL, but doesn't point to a valid address either. Segmentation violation ensues.
You should initialise all cars, not only INCREMENT - 2. Alternatively, you could initialise your cars to zero by calling memset before your initialisation:
memset(CAR_ARRAY, 0, sizeof(Car) * INCREMENT);
As an aside, the way you deal with getCarName is rather shaky as well. At the moment, your name is a pointer to a string literal. Your local variable carName does a half-hearted double duty: You try to pass it by reference (but essentially you don't) and you also return it.
Basically, you could do this in one of two ways. The easier one here is to return a pointer. in that case, you don't have to pass any string:
char *getCarName(int var)
{
static char *names[3] = {"Toyota", "Dodge", "Peugeot"};
return names[var % 3];
}
and call it like so:
char *carName = getCarName(&carName, a);
Alternatively, you could pass a char pointer by reference, i.e. as pointer to pointer to char. In that case, you don't have to return anything:
void getCarName(char **name, int var)
{
static char* names[3] = {"Toyota", "Dodge", "Peugeot"};
*name = names[var % 3];
}
Call it like so:
char *carName;
getCarName(&carName, a);
There are other scenarios here, for example if you just pass a char pointer and have getCarName fill it, but I'll leave that for now - it would make everything even more complicated.
typedef struct
{
char *s;
char d;
}EXE;
EXE *p;
For the above struct how do I initialize the structure with pointer? I know for a non-pointer we do EXE a[] = { {"abc",1}, {"def",2} }; . Similarly Is it possible with a pointer after allocating the memory? Say like p[] = { {"abc",1},.. so on} . Basically I want to initialize dynamically. Thanks.
We can initialise the structure with pointer as below
example:
int i;
char e[5]="abcd";
EXE *p=malloc(sizeof(*p));
for(i = 0;i < 5;i++)
*(p+i)=(EXE){e,i+48};
First you need to allocate some memory for that char * and after that use strcpy library function to copy data for structure element.
p->s = strcpy(s,str); //where str source, from where you need to copy the data
I hope this will help. Though I can give you full code for that, But I want you to try.
You can use this
Dynamically allocate C struct?
and it is a duplicate question.
You have to understand how do allocated pointer works:
Suppose you've allocated memory for three structs Ptr = malloc(3*sizeof(EXE)).
Then when you add 1 to Ptr, it comes to the next struct. You have a block of memory divided by 3 (3 smaller blocks of memory for each struct).
So, need to access to the elements of the 1st struct and then move the pointer to the next one.
Here you can understand how it works:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char *s;
char d;
} EXE;
int main()
{
int i;
EXE *Ptr;
Ptr = malloc(3*sizeof(EXE)); // dymnamically allocating the
// memory for three structures
Ptr->s = "ABC";
Ptr->d = 'a';
//2nd
Ptr++; // moving to the 2nd structure
Ptr->s = "DEF";
Ptr->d = 'd';
//3rd
Ptr++; // moving to the 3rd structure
Ptr->s = "XYZ";
Ptr->d = 'x';
//reset the pointer `Ptr`
Ptr -= 2; // going to the 1st structure
//printing the 1st, the 2nd and the 3rd structs
for (i = 0; i < 3; i++) {
printf("%s\n", Ptr->s);
printf("%c\n\n", Ptr->d);
Ptr++;
}
return 0;
}
Notice:
- If you have a variable of a struct use . opereator to access to the elements.
- If you have a pointer to a struct use -> operator to access to the elements.
#include <stdio.h>
#include <stdlib.h>
struct EXE {
int a;
};
int main(){
struct EXE variable;
struct EXE *pointer;
pointer = malloc(sizeof(struct EXE)); // allocating mamory dynamically
// and making pointer to point to this
// dynamically allocated block of memory
// like here
variable.a = 100;
pointer->a = 100;
printf("%d\n%d\n", variable.a, pointer->a);
return 0;
}
I am a newcomer to the world of C. I am self-teaching and would appreciate some help with a couple of questions.
This program is a simplified variation on one written in this example to demonstrate the use of pointers with arrays of structs. The things I'm having trouble getting my head around are:
How the array is incremented in the first for loop. The ++ operator is used directly on the array of structs whereas I would have expected the need to do something more like in_p[i] inside the loop (with i being an int that get incremented).
The way that the comparison is being made in this loop. I didn't think that in_p < &ar[ARSIZE] would be possible since both are of type struct wp_char. What is actually being compared here?
Both the example in the book and my example compile and run.
Thank you.
#include <stdio.h>
#include <stdlib.h>
#define ARSIZE 5
struct wp_char{
char wp_cval;
short wp_font;
short wp_psize;
}ar[ARSIZE];
void infun(struct wp_char *, char cval, int font, int psize);
int main(void)
{
struct wp_char wp_tmp, *lo_indx, *hi_indx, *in_p;
char c[] = {'a','b','c','d','e'};
int i1[] = {2,3,4,5,6};
int i2[] = {7,8,9,10,11};
int i = 0;
for(in_p = ar; in_p < &ar[ARSIZE]; in_p++){
infun(in_p, c[i], i1[i], i2[i]);
i++;
}
int j;
for(j=0;j<ARSIZE;j++)
{
printf("%c\n",c[j]);
printf("%d\n",i1[j]);
printf("%d\n",i2[j]);
puts("\n");
}
exit(0);
}
void infun( struct wp_char *inp, char cval, int font, int psize)
{
`
inp->wp_cval = cval;
inp->wp_font = font;
inp->wp_psize = psize;
return;
}
Question 1:
In C pointer arithmetic, ++ and -- increment and decrement a pointer by the size of the thing being pointed to, not by a byte (or some other aribitrary measure). See e.g. http://www.eskimo.com/~scs/cclass/notes/sx10b.html and http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/pointer.html.
Note that this also applies to plain old addition and subtraction too:
float x[10];
float xPtr = &x[0]; // OR could write simply "float xPtr = x;"
xPtr = xPtr + 1; // xPtr now points at x[1]
xPtr = xPtr - 1; // xPtr now points at x[0] again
xPtr = xPtr + 9; // xPtr now points at last item in the array, x[9]
Question 2:
They're not of type struct wp_char, they're of type struct wp_char*, i.e. pointer to that struct. Think of them as a number pointing to a memory location containing one of those structs. You can compare two memory location for equality.
I'm trying to split a string every X amount of characters, and then store each line in an array of structs. However, I'm wondering what would be a short and efficient way of doing it. I thought that maybe I could use sscanf, but not very sure how to. Any help will be appreciated. So far I have:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct st {char *str;};
int main ()
{
struct st **mystruct;
char tmp[] = "For configuration options (arch/xxx/config.in, and all the Config.in files),somewhat different indentation is used.";
size_t max = 20, j = 0; // max length of string
size_t alloc = strlen(tmp)/max + 1;
mystruct = malloc(alloc * sizeof *mystruct);
for (j = 0; j < alloc; j++)
mystruct[j] = malloc(sizeof *mystruct[j]);
const char *ptr = tmp;
char field [ max ];
int n;
while (*ptr != '\0') {
int line = sscanf(ptr, "%s", field, &n); // not sure how to use max in here
mystruct[j]->str = field;
field[0]='\0';
if (line == 1)
ptr += n;
if ( n != max )
break;
++ptr;
++j;
}
return 0;
}
So when I iterate over my struct, I can get something like:
For configuration op
tions (arch/xxx/conf
ig.in, and all the C
onfig.in files),some
what different inden
tation is used.
You could use strncpy.
FYI:
char field [ max ];
while (...) {
mystruct[j]->str = field;
Two problems with this: (1) every struct in your array is going to end up pointing at the same string, which will have the value of the last thing you scanned, (2) they are pointing to a variable on the stack, so when this function returns they will be trashed. That doesn't manifest itself visibly here (e.g. your program doesn't explode) because the function happens to be 'main', but if you moved this to a separate routine and called it to parse a string, you'd get back garbage.
mystruct doesn't need to be pointer to pointer. For a 1D array, just allocate a block N * sizeof *myarray for N elements.
A common C idiom when dealing with structs is to use typedef so you don't have to type struct foo all the time. For instance:
typedef struct {
int x, y;
} point;
Now instead of typing struct point pt you can just say point pt.
If your string is not going to change after you split it up, I'd recommend using a struct like this:
struct st {
char *begin;
char *end;
};
or the alternative:
struct st {
char *s;
size_t len;
};
Then instead of creating all those new strings, just mark where each one begins and ends in your struct. Keep the original string in memory.
One option is to do it character-by-character.
Calculate the number of lines as you are currently doing.
Allocate memory = (strlen(tmp) + number_of_lines) * sizeof(char)
Walk through your input string, copying characters from the input to the newly allocated memory. Every 20th character, insert a null byte to delimit that string. Save a pointer to the beginning of each line in your array of structs.
Its easy enough?
#define SMAX 20
typedef struct {char str[SMAX+1];} ST;
int main()
{
ST st[SMAX]={0};
char *tmp = "For configuration options (arch/xxx/config.in, and all the Config.in files),somewhat different indentation is used.";
int i=0,j;
for( ; (st[i++]=*(ST*)tmp).str[SMAX]=0 , strlen(tmp)>=SMAX; tmp+=SMAX );
for( j=0;j<i;++j )
puts(st[j].str);
return 0;
}
You may use (non C standard but GNU) function strndup().
#define _GNU_SOURCE
#include <string.h>
struct st {char *str;};
int main ()
{
struct st *mystruct; /* i wonder if there's need for double indirection... */
char tmp[] = "For configuration options (arch/xxx/config.in, and all the Config.in files),somewhat different indentation is used.";
size_t max = 20, j = 0; // max length of string
size_t alloc = (strlen(tmp) + max - 1)/max; /* correct round up */
mystruct = malloc(alloc * sizeof mystruct);
if(!mystruct) return 1; /* never forget testing if allocation failed! */
for(j = 0; j<alloc; j++)
{
mystruct[j].str = strndup(tmp+alloc*max, max);
}
}