1

i find there if I create a static array like char a[10] and fill it up by a for loop (like fill 'a' to each space). Then pass its first element's address to a function like add(char* b). I find the elements in the array will change. I am confusing about it. Here is my code and some output by gdb.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct test{
char a[5];
char b[5];
char c[5];
char d[5];
};
void add (char* n, struct test* test1){
   for (int i=0; i<5; i++){
    test1->a[i]=*n;
    n++;
   }
   for (int i=0; i<5; i++){
    test1->b[i]=*n;
    n++;
   }
   for (int i=0; i<5; i++){
    test1->c[i]=*n;
    n++;
   }
   for (int i=0; i<5; i++){
    test1->d[i]=*n;
    n++;
   }
   printf("%s\n", test1->a);
   printf("%s\n", test1->b);
   printf("%s\n", test1->c);
   printf("%s\n", test1->d);
 }
 int main(){
   char k[20];
   struct test test1;
   for(int i=0; i<20; i++){
     scanf("%c", &k[i]);
   }
   add(k, &test1);
 }

when I use gdb to print the n, I got 0x7fff5fbffb20 "abcdefghij1234567890\377\177". So why there is "\377\177"? And also, the output of this program is

habcdefghij1234567890
fghij1234567890
1234567890
67890ere

why?

1 Answer 1

1
printf("%s\n", test1->a);

By using the s conversion specifier you say to the compiler that test1->a is a string but your arrays don't have a null terminator character: they are not strings and the printf is invoking undefined behavior.

Reserve an additional extra byte set to 0 in your arrays or print them like this:

printf("%.*s\n", sizeof test1->a, test1->a);

the above call print a non null terminated array.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help, it works. By the way, could you help me to understand why the elements in array k changed after I passed it into the add function?( I mean it shows that after the original string there is \377\117")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.