Passing a element of a char array into another position - c

So i have a struct with the following elements:
typedef struct loja{
int numero;
char nome[MAX];
float area;
float faturacao[12];
} Loja[N];
i declared an array vetC[ ] for the struct and my next step was to eliminate a posicion of that array
int EliminarComum(int c,Loja vetC[]){
int posicao, i,a;
posicao = MostrarComum(c,vetC); ///only for the user to choose the position he wishes to eliminate.
if (posicao > c)
printf("can't delete.\n");
else {
for (i = posicao - 1; i < c - 1; i++){
vetC[i]->numero = vetC[i+1]->numero;
vetC[i]->nome = vetC[i+1]->nome;
vetC[i]->area = vetC[i+1]->area;
for(a=0;a<12;a++)
vetC[i]->faturacao[a] = vetC[i+1]->faturacao[a];
c--;
}
}
return c;
}
and in the line of vetC[i]->nome = vetC[i+1]->nome; gives me the error
error: assignment to expression with array type

You cannot assign arrays, but you could assign complete struct loja-objects:
vetC[i] = vetC[i+1];
Conver, for example, the following simple program, which illustrates how an assignment of struct-objects works, while an assignment of a char-array fails:
struct testStruct {
int x;
char str[10];
};
int main() {
struct testStruct t1 = { 10, "Hello" };
struct testStruct t2;
t2 = t1; // legal.
char str1[10] = "Hello";
char str2[10];
// str2 = str1; // illegal; arrays cannot be assigned.
strcpy(str2,str1); // legal (as long as str1 is a valid string)
}

Related

Passing by Struct pointer is returning wrong value

I am new to C but I am trying to edit a struct in a different function. I can print the value of the struct correctly from the target function readCoordinate but when execution returns to the main function the values of the struct changes to a seemingly random integers.
This is the full code below.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int X;
int Y;
} Coordinate;
void buff_clr(void)
{
char junk;
do{
junk=getchar();
}while(junk!='\n');
}
int main()
{
Coordinate carrierStart = {0,0};
printf("Input Start coordinate for Carrier (example - B2) \n");
readCoordinate(&carrierStart);
printf("%d, %d \n", carrierStart.X, carrierStart.Y);
}
void readCoordinate(Coordinate *cood){
char str[2];
scanf("%s",&str);
buff_clr();
if (isalpha(str[0]) )
{
str[0] = tolower(str[0]);
findChar(str[0], &cood->X);
cood->Y = (str[1] - '0') - 1;
}
else
{
printf("\n Please Enter Valid Coordinate");
exit(EXIT_SUCCESS);
}
printf("%d, %d \n", cood->X, cood->Y);
return;
}
void findChar(char find, int *x){
char vertical_letters[10] = {'a','b','c','d','e','f','g','h','i','j'};
for (int i = 0; i < 10; i++)
{
if (find == vertical_letters[i])
{
*x = i;
return;
}
}
*x = -1;
}
input of b2 should print 1,1 which is correct in function (readCoordinate) but wrong in Main.
The part
char str[2];
scanf("%s",&str);
is wrong because
&str has type char(*)[2], but %s in scanf expects char*. Passing data having the wrong type like this invokes undefined behavior.
char str[2]; is too short to store 2-character strings like b2 because there is no room for the terminating null character. You have to allocate enough elements.
You should specify the maximum length to read (the length of buffer minus one) to prevent buffer overrun.
It should be:
char str[3];
scanf("%2s",str);

How can I initialize an array of pointers pointing to a struct?

I have the following struct:
struct clientDetails
{
int socket;
char* port;
char* IP;
char* hostName;
int msgSentCount;
int msgRecvCount;
char* status;
char bufferMsg[BUFFER_SIZE];
char blockedUser[4];
int blockedCount;
};
And I have an array of pointers:
struct clientDetails* allClients[4];
How can I initialize all the array elements of allClients to have default values?
I have tried the following but I am getting 'incomplete definition of type struct':
for(int i = 0; i<4; i++) {
allClients[i]->socket = 0;
allClients[i]->port = NULL;
allClients[i]->IP = NULL;
allClients[i]->hostName = NULL;
allCLients[i]->msgSentCount = 0;
allClients[i]->msgRecvCount = 0;
allClients[i]->status = NULL;
allClients[i]->bufferMsg = "";
allClients[i]->blockedUser = {"","","",""};
allClients[i]->blockedCount = 0;
}
For one thing, you need to allocate storage for that struct... right now all you have a single pointer. Right at the top of your loop, you should do something like:
allClients[i] = malloc(sizeof(clientDetails));
It's been a while since I've done structs in "C", but you could/should probably typedef your struct as well.

Pointer is changing after function call, C

So I've written this program to represent a car park as a bitset, each space in the car park being one bit. I have a checkSpace function to check if a space is occupied or not and for some reason the pointer to my car park bitset changes or the data changes after I pass it into the function. To test it I set up the car park, I checked a space, then checked it again immediately after and for some reason the return value is changing when it shouldn't be. Any help would be appreciated!
struct carPark{
int spaces, levels;
unsigned char * park;
};
struct carPark * emptyCarPark(int levels, int spaces){
int chars = (spaces*levels)/8;
if((spaces*levels)%8 != 0){
chars++;
}
unsigned char park[chars];
for (int i = 0; i < chars; ++i){
park[i] = 0;
}
unsigned char * ptr = &park[0];
struct carPark * myPark = malloc(sizeof(struct carPark));
myPark->park = ptr;
myPark->spaces = spaces;
myPark->levels = levels;
return myPark;
}
int checkSpace(int level, int spaceNum, struct carPark * carpark){
int charPosition = ((level*carpark->spaces) + spaceNum)/8;
int bitPosition = ((level*carpark->spaces) + spaceNum)%8;
if(carpark->park[charPosition]&&(1<<bitPosition) != 0){
return 1;
}
return 0;
}
int main(int argc, char const *argv[]){
struct carPark * myPark = emptyCarPark(5,20);
printf("1st check: %d\n",checkSpace(1,1,myPark));
printf("Second check: %d\n",checkSpace(1,1,myPark));
return 0;
}
So when I run the program I get:
1st check: 0
Second check: 1
Look at the code below - in emptyCarPark() you are allocating the park array on the stack, and then returning a pointer to it. As soon as the function returns, the park array is no longer allocated and you have a dangling pointer - for more information, see: Cause of dangling pointers (Wikipedia)
unsigned char park[chars];
for (int i = 0; i < chars; ++i){
park[i] = 0;
}
// This is the pointer to an object on the stack.
unsigned char * ptr = &park[0];
struct carPark * myPark = malloc(sizeof(struct carPark));
myPark->park = ptr;

How to access nested structure using pointer and array?

typedef struct
{
unsigned int a;
unsigned char b[10];
unsigned char c;
}acc1;
typedef struct
{
unsigned char z[10];
acc1 *x,y[10];
}acc2;
extern acc2 p[2];
I want to access struct acc1 variables from acc2 array p[2].
I'm getting segmenatation faults when I do it. Please guide on how to do this
To access y's elements do:
char c = p[some index between 0 and 1].y[some index between 0 and 9].c
To access elements referred to by x do:
size_t i = some index between 0 and 1;
p[i].x = malloc(somenumber_of_elements * sizeof *p[i].x);
if (NULL == p[i].x)
{
abort(); /* Failure to allocate memory. */
}
char c = p[i].x[some index less then somenumber_of_elements].c;
Referring kabhis comment
p[0].x->c is it not correct ?
Assuming the allocation above with somenumber_of_elements greater 0, then:
char c = p[i].x[0].c;
is equivalent to
char c = p[i].x->c;
and for somenumber_of_elements greater 1
char c = p[i].x[1].c;
is equivalent to
char c = (p[i].x + 1)->c;
and so on ...

Storing the 2 arrays in a datastructure

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;
}

Resources