0

important: I don't have a deep understanding of malloc so try to put things as simple as possible Greetings, I want to create a dynamic array of strings (using malloc) and then print those strings out (for starters).

That's what I have

int main(){
    char **namesofcolumns = malloc(4 * sizeof(char*));
    for(int i = 0; i < 4; i++){
        namesofcolumns[i] = malloc(20 * sizeof(char));
    }
    int count = 1;
    for(int i = 0; i < 4; i++){
        printf("Enter %d column name\n", count);
        scanf("%s", namesofcolumns[i]);
        count++;
    }

I probably have errors here already. How do I print entered strings out?

2
  • Printf wants a char*. Ask yourself what the types are of namesofcolumns and namesofcolumns[i] Commented Mar 31, 2024 at 12:32
  • @xing, thanks a lot. Now I need to return this array namesofcolumns and than use it in a function that will print out a table header ''' void printHeader(char namesOfRows[4][20]){ printf("__________________________________\n"); for(int itemNo = 0; itemNo < 4; itemNo++){ for(int itemLen = 0; itemLen < strlen(namesOfRows[itemNo]); itemLen++){ printf("%c", namesOfRows[itemNo][itemLen]); } printf(" "); printf("|"); printf(" "); } } ''' how do I return this array namesofcolumns? Commented Apr 2, 2024 at 9:44

1 Answer 1

0

namesofcolumns have 4 string pointers so you have to derefence it access the value stored in namesofcolumns.Add the following code to you program to see expected result.

count = 1;
for(i = 0;i < 4;i++){
    printf("Name %d :%s\n",count,*namesofcolumns);
    namesofcolumns++;
    count++ ;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Since none but namesofcolumns point at the allocated memory, this will create memory leaks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.