Home > Enterprise >  how do I access a character from 2-D char string
how do I access a character from 2-D char string

Time:01-08

#include <stdio.h>
#include <string.h>
#define max 50
#define len 30
char text[max][len];
void main(){
    register int i;
    printf("Enter an empty line to quit\n");
    for(i =0 ;i<max;i  ){
        gets(text[i]);
        if(!*text[i]){break;}
    }
puts(text[1][0]);/*I want to display first character of second string but it doesn't print anything. Why??*/
}

how do i access character or part of string from array of string

CodePudding user response:

For starters according to the C Standard the function main without parameters shall be declared like

int main( void )

The function gets is unsafe and is not supported by the C Standard. Instead use standard C function fgets.

The function puts expects an argument of the pointer type char * that points to a string. However you are passing an object of the type char

puts(text[1][0]);

that invokes undefined behavior.

Also declare variables in minimum scope where they are used. There is no great sense to declare the array text in the file scope.

The program can look the following way

#include <stdio.h>

#define MAX 50
#define LEN 30

int main( void )
{
    char text[MAX][LEN] = { 0 };

    puts( "Enter an empty line to quit" );

    size_t i = 0;

    while ( i < MAX && fgets( text[i], LEN, stdin ) != NULL && text[i][0] != '\n' ) 
    {
          i;
    }

    if ( !( i < 2 ) ) printf( "%c\n", text[1][0] );
}

Pay attention to that the function fgets can store the new line character '\n' in the suppled array.

If you want to remove it then you can write for example

#include <string.h>

//...

text[i][ strcspn( text[i], "\n" ) ] = '\0';

CodePudding user response:

In your code, puts(text[1][0]) is trying to print a text[1][0] which is a char, and puts only accepts an char*, leading to a segmentation fault on my computer.

But, printf allows you to print an char. (Also the gets function puts input in text[0] instead of text[1])

Fixed code:

#include <stdio.h>
#include <string.h>
#define max 50
#define len 30
char text[max][len];
void main(){
    register int i;
    printf("Enter an empty line to quit\n");
    for(i =1 ;i<max;i  ){ // set i to 1 because gets() is putting input into text[0] not text[1]
        gets(text[i]);
        if(!*text[i]){break;}
    }
printf("%c\n", text[1][0]); /* printf allows you to print char */
}

Note: as said in the comments of the question, you can also use putchar() to print one character.

Input:

s

Output:

s
  • Related