#looping Struct

20 messages · Page 1 of 1 (latest)

ivory willow
#

In the below code I can't do this part charMem[i].charVal = s[i]; it shows "assignment to ‘char *’ from ‘char’ makes pointer from integer without a cast". How to fix this issue? I want to print all characters of "delete" using struct. Thanks in advance

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct Characters
{
int count;
char* charVal;
};

int main() {
int totalValues = 7;
struct Characters *charMem = malloc(sizeof(struct Characters)*totalValues);

char s[] = "delete";
int slen = strlen(s);

for(int i=0;i<slen;i++) {
charMem[i].count = i;
charMem[i].charVal = s[i];
}

for(int i=0;i<5;i++) {
printf("count %d and charVal %s\n", charMem[i].count, charMem[i].charVal);
}

free(charMem);
return 0;
}

pliant hingeBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

pliant hingeBOT
#

In the below code I can't do this part ```cpp
charMem[i].charVal = s[i];
it shows
"assignment to ‘char *’ from ‘char’ makes pointer from integer without a "
"cast".How to fix this issue
? I want to print all characters of "delete" using struct.Thanks in advance
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

  struct Characters {

int count;
char* charVal;
};

int main() {
int totalValues = 7;
struct Characters* charMem = malloc(sizeof(struct Characters) * totalValues);

char s[] = "delete";
int slen = strlen(s);

for (int i = 0; i < slen; i++) {
charMem[i].count = i;
charMem[i].charVal = s[i];
}

for (int i = 0; i < 5; i++) {
printf("count %d and charVal %s\n", charMem[i].count, charMem[i].charVal);
}

free(charMem);
return 0;
}

dumbEngineer
full harbor
#

well thats fucked

full harbor
ivory willow
#

I want to create a struct and add each character of string "whatever", is there any other way than what you mentioned

full harbor
#

you could just include the array in each struct

#

eg

#

struct Characters {
  int count;
  char charVal[100];
};```
full harbor
ivory willow
#

I changed it to array and did this
strcpy(per[i].charVal,s[i]);
it doesn't work but when I do strcpy(per[i].charVal,"k"); it works

full harbor
#

are you trying to copy the entire string "delete" into each of the structs?

#

or just a single character?

ivory willow
#

I want this
count : 0,
char: d

count : 1,
char: e

count : 2,
char: l

etc...

full harbor
#

okay, if you only want a single character in each struct, then you shouldnt use the array or a pointer

#

just c struct Characters { int count; char charVal; };

#

that should work with your original code

ivory willow
#

yes that worked ! Thanks much!