Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

237
Views
¿Por qué las cadenas no se imprimen en mi matriz?
#include<stdio.h> int main() { char arr[100], i; int n; printf("Enter the size of the Array: "); scanf("%d", &n); printf("\nEnter the Strings in the Array\n"); for(i=0; i<n; i++) { scanf("%s", &arr[i]); } for(i=0; i<n; i++) { printf("%s", arr[i]); } return 0; }

¿Por qué la ejecución de este código simplemente se detiene después de tomar la entrada de variables de cadena? ¿Por qué no está imprimiendo la cadena en una matriz?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Está sobrescribiendo la misma cadena cada vez, pero comenzando una más profunda en la matriz en cada iteración. Puede ver el problema más fácilmente cuando la matriz tiene un tamaño de 4.

 char arr[4], i; int n = 4; printf("\nEnter the Strings in the Array\n"); for(i=0; i<n; i++) { scanf("%s", &arr[i]); }

Ahora, la primera vez que ingrese una cadena de más de 3 caracteres, su aplicación fallará. La segunda vez más de 2 caracteres porque empiezas en la misma cadena +1 byte. La dirección de arr + 1.

La tercera vez solo 1 byte sigue siendo válido, etc.

Cambie su matriz a algo como char arr[100][100]; Entonces tienes matrices de 100 caracteres de matriz de 100 grandes. También elimine el ampersand del scanf ya que en ese punto arr[i] ya es una dirección.

 scanf("%s", arr[i]);

Igual que:

 scanf("%s", &arr[i][0]);
over 4 years ago · Santiago Trujillo Report

0

Fuente:

 #include<stdio.h> int main(){ //stores the size of the array int n; printf("Enter the size of the Array: "); scanf("%d", &n); //n represents number of strings you want to store char arr[n][100], i; printf("\nEnter the Strings in the Array\n\n"); for(i=0; i<n; i++){ scanf("%s", arr[i]); } printf("\nOutput:\n\n"); for(i=0; i<n; i++){ printf("%s\n", arr[i]); } return 0; }

Producción:

 $ gcc array.c && ./a.out Enter the size of the Array: 3 Enter the Strings in the Array first second third Output: first second third

Si desea escanear espacios también:

Fuente:

 #include<stdio.h> int main(){ //stores the size of the array int n; printf("Enter the size of the Array: "); scanf("%d", &n); //n represents number of strings you want to store char arr[n][100], i; printf("\nEnter the Strings in the Array\n\n"); for(i=0; i<n; i++){ //flushs the previous buffer getchar(); //It will read spaces now scanf("%[^\n]s", arr[i]); } printf("\nOutput:\n\n"); for(i=0; i<n; i++){ printf("%s\n", arr[i]); } return 0; }

Producción :

 $ gcc array.c && ./a.out Enter the size of the Array: 3 Enter the Strings in the Array first string second third string... Output: first string second third string...
over 4 years ago · Santiago Trujillo Report

0

La línea

 char arr[100];

solo asignará espacio para una sola cadena de hasta 100 caracteres (99 caracteres más el carácter nulo de terminación). Si desea asignar espacio para 100 cadenas de 100 caracteres cada una, debe escribir esto en su lugar:

 char arr[100][100];

Otro problema es que usar scanf con el especificador de formato de conversión %s solo leerá una sola palabra, no una línea completa de entrada. Si desea leer una línea completa de entrada, debe usar la función fgets en su lugar.

Aquí hay un programa de ejemplo:

 #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_STRINGS 100 #define MAX_STRING_LENGTH 100 int main( void ) { char strings[MAX_STRINGS][MAX_STRING_LENGTH]; int n; int c; //read number of strings printf( "Enter the number of strings: " ); if ( scanf( "%d", &n ) != 1 ) { printf( "input error!\n" ); exit( EXIT_FAILURE ); } //verify that number of strings is acceptable value if ( ! ( 0 <= n && n <= MAX_STRINGS ) ) { printf( "Input must be between 0 and %d.\n", MAX_STRINGS ); exit( EXIT_FAILURE ); } //discard remainder of input line do { c = getchar(); } while ( c != EOF && c != '\n' ); //input all strings for ( int i = 0; i < n; i++ ) { //prompt user for input printf( "Enter string #%d: ", i + 1 ); //attempt to read one line of input if ( fgets( strings[i], sizeof *strings, stdin ) == NULL ) { printf( "input error!\n" ); exit( EXIT_FAILURE ); } //remove newline character from input strings[i][strcspn(strings[i],"\n")] = '\0'; } //output all strings printf( "\nOutput:\n\n" ); for( int i = 0; i < n; i++ ) { printf( "%s\n", strings[i] ); } }

Este programa tiene el siguiente comportamiento:

 Enter the number of strings: 3 Enter string #1: This is a test. Enter string #2: This is another test. Enter string #3: This is yet another test. Output: This is a test. This is another test. This is yet another test.
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!