2017-02-18 1 views
0

Je sais que nous sommes en mesure de changer une chaîne grâce à une fonction comme celui-ciComment modifier un tableau 2D passé à une fonction

void c(char *s)                    
{                        
    int i = 0;                     

    while (s[i])                     
    s[i++] = 's';                    
}     



int  main()                     

    {                        
     char str[] = "hello";                   

     c(str);                      
     printf("%s\n", str);                   
     return (0);                     
    } 

Dans ce cas, il imprimera « sssss ». Mais comment puis-je modifier un tableau 2d de la même façon que pour une chaîne? Je veux dire sans retourner le tableau.

void c(char **s)                   
{                        
    int i = 0;                    
    int j = 0;                    

    while (s[i])                    
    {                       
     j = 0;                     
     while (s[i][j])                   
     {                      
      s[i][j++] = 's';                 
     }                      
     i++;                     
    }                       

}                        

int  main()                    
{                        
    char tab[2][2];                    
    tab[0][0] = 'a';                   
    tab[0][1] = 'b';                   
    tab[1][0] = 'c';                   
    tab[1][1] = 'd';                   
    c(tab);                      
    printf("%c%c\n%c%c", tab[0][0], tab[0][1], tab[1][0], tab[1][1]);       
    return (0);                     
} 

Voici une idée de comment nous pourrions le faire.

J'espère avoir été assez clair?

Répondre

0

La définition doit contenir la longueur. A la suite sera une bonne lecture: http://www.firmcodes.com/pass-2d-array-parameter-c-2/

vide c (char (* s) [longueur])

#include <stdio.h> 
void c(int len, char (*s)[len]) 
{ 
    int i = 0; 
    int j = 0; 

    while (i < len) 
    { 
     j = 0; 
     while (s[i][j]) 
     { 
      s[i][j++] = 's'; 
     } 
     i++; 
    } 

} 

int  main() 
{ 
    char tab[2][2]; 
    tab[0][0] = 'a'; 
    tab[0][1] = 'b'; 
    tab[1][0] = 'c'; 
    tab[1][1] = 'd'; 
    c(2, tab); 
    printf("%c%c\n%c%c", tab[0][0], tab[0][1], tab[1][0], tab[1][1]); 
    return (0); 
} 
0

Bien sûr, c'est pareil. Avec n'importe quel nombre de dimensions.

void c(char **s, int stringCount) 
{ 
    int i = 0, j = 0; 

    for (j = 0; j < stringCount; ++j) 
    { 
     i = 0; 
     while (s[j][i]) 
     { 
      s[j][i++] = 's'; 
     } 
    } 
} 

int  main() 
{ 
    char *tab[2] = { "str1", "str2" }; 
    c(tab, 2); 
    printf("%c%c\n%c%c", tab[0][0], tab[0][1], tab[1][0], tab[1][1]); 
    printf("%s\n%s", tab[0], tab[1]); 
    getchar(); 
    return (0); 
} 
+0

Comment puis-je appeler la fonction? J'ai essayé func (s) mais ça ne marche pas :( – Beben

+0

Merci pour votre réponse! :) – Beben