Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

c - string array values are not printing

Do I need to include some spec library to work with 2D arrays?

Why different values are printed for similar definitions?

  • printf("%s", bbit[0]) for bbit array prints 0001001000110100mmmm0110011110001001101010111100110111101111?Bt?,
  • printf("%s", arr[0]) for arr prints 0000.

what could be the reason?
How to print the strings from array?
How to print byte representation of array[i] variable or any other variable?

#include <stdio.h> /* printf */
#include <stdint.h> //int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t, uint32_t, uint64_t  
#include <string.h>  /* strcat */
#include <stdlib.h>  /* strtol */

void main() {
    char bbit[16][4] = {
         "0000", "mmmm", "0010", "0011", // 0,1,2,3
         "0100", "0101", "0110", "0111", // 4,5,6,7
         "1000", "1001", "1010", "1011", // 8,8,10,11
         "1100", "1101", "1110", "1111"  // 12,13,14,15
    }; 

    char* b4 = bbit[0];
    printf( "'%s'  %p  %d,  '%s' 
", b4, b4, *b4, bbit[0] ); 

    char* b5 = bbit[1];
    printf( "'%s'  %p  %d,  '%s' 
", b5, b5, *b5, bbit[1] ); 

    //prints '00000001001000110100mmmm0110011110001001101010111100110111101111?Bt?'  0x7ffc74421160  48,  '00000001001000110100mmmm0110011110001001101010111100110111101111?Bt?' 
    //prints '0001001000110100mmmm0110011110001001101010111100110111101111?Bt?'  0x7ffc74421164  48,  '0001001000110100mmmm0110011110001001101010111100110111101111?Bt?' 

    char arr[2][4] = { "0000",  "mmmm", };
    printf("'%s' has length %ld
", arr[0], strlen(arr[0]));
    printf("'%s' has length %ld
", arr[1], strlen(arr[1]));

    //prints '0100mmmm' has length 8
    //prints 'mmmm' has length 4
}
question from:https://stackoverflow.com/questions/66065717/string-array-values-are-not-printing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The 2D length has to be increased by one = 5. Because each string is terminated with a null character .

char bbit_rep[16][5] = {...}
//prints '0000'  0x7ffea750e4f0  48,  '0000'  

char arr[2][5] = { "0000",  "mmmm", };
printf("'%s' has length %ld
", arr[0], strlen(arr[0]));
//prints '0000' has length 4

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...