0

I am trying to print the names of my array with a for but the output gives me random letter and signs, I cant cast it correctly to print the names of the struct.

typedef struct{
   // uint8_t name;
    char *name[100];
    char *lasTName[100];
}resFrame;

resFrame serverFrame;

for(int j=0;j<10;j++){
   printf("%s",(char *)&serverFrame.name[j]);  
}

Output:

�7��

I try with a for and with a other pointer but it gives me the same problem and sometimes a core dumped

3
  • 4
    Show how the data members are initialized. Commented Apr 5, 2023 at 15:47
  • 2
    delete the & ...? Commented Apr 5, 2023 at 15:47
  • 1
    How's name allocated, most probably heap-allocated using malloc() ?? Better use char ** to remove confusion. Commented Apr 5, 2023 at 16:26

1 Answer 1

2

If the data member name declared like

char *name[100];

indeed contains pointers to strings then you need to write for example

printf("%s\n", serverFrame.name[j]);

The conversion specifier expects an argument of the type char *.

The expression used by you &serverFrame.name[j] has the type char **. Casting it to the type char * results in undefined behavior because the address of the pointer is considered by the call of printf as an address of the first element of a string.

4
  • If i try to printf("%s\n", serverFrame.name[j]); it gives me a segmentation fault
    – cesar
    Commented Apr 5, 2023 at 16:32
  • @cesar I showed you how correctly call printf. I do not know how the array of pointers actually initialized. Commented Apr 5, 2023 at 16:37
  • 1
    @cesar I advice you to close this question because as is it is answered and to ask a new question with at least the correct shown call of printf but including a minimal code that demonstrates how the data member were initialized. It seems pointers stored in the arrays are invalid. Commented Apr 5, 2023 at 17:57
  • @cesar Vlad from Moscow's answer is correct for fixing the printf problem. If after that fix you get a seg fault, it is a second problem. That second problem is likely due to incorrect setup of the severFrame object. The original post does not contain appropriate information relating to that.
    – Avi Berger
    Commented Apr 5, 2023 at 18:04

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.