Zuoyang Ding
Zuoyang Ding

Reputation: 77

static array pass to a function in c

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?

Upvotes: 1

Views: 75

Answers (1)

ouah
ouah

Reputation: 145829

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.

Upvotes: 1

Related Questions