-1

Professor give me a homework about malloc, dynamic memory allocate... So He give me some hints about code but I can't understand his code and hints. I think my code needs another 'def' or 'for loop'... Anyway.

question Now I can gets_s some string with pointer. but I can't build. Print like alien language... last of this page I hope this code would be work. for (j=0;j<3;j++) printf("your sentence is %s ", *parray[i])

I tried some of codes with friends. he also can't figure out.. Professor told me This code is for beginner, "IT's easy to solve"

#include<stdio.h>
#include<stdlib.h>

void main() {
    char* parray[3];
    int i, j;
    char str[70]; // temporary save place
    for (i = 0; i< 3; i++) {        //
        printf("sentence, please. : ");
        gets_s(str, sizeof(str));   //dynamic memory allocate
        parray[i] = (char*)malloc(sizeof(char)**str);
        printf("\n");


free(parray[i]);

I hope this code work.

for (j=0;j<3;j++)
    printf("your sentence is %s ", *parray[i])
Bodo
  • 9,287
  • 1
  • 13
  • 29
Kihyeon Kim
  • 23
  • 1
  • 5

1 Answers1

1

You should be allocating the amount of characters there was in the input string, +1 for the null terminator.

parray[i] = malloc(strlen(str)+1);

Then copy the data from temporary str to the new memory location.

Also avoid gets_s and use fgets instead. The bounds-checking interface of C11 is poorly supported in general, but this particular function was just some placeholder when rewriting old code using obsolete gets.

Lundin
  • 195,001
  • 40
  • 254
  • 396
  • thanks! I'll try it again! and, If you had time, can you tell me about how to save another memory location? just parray[i] = another location[j] would be okay? – Kihyeon Kim Oct 18 '19 at 10:55
  • I don't like the `_s` functions, either, but if you tell someone to use `fgets`, you also have to teach them how to strip the newline. (An unfortunate nuisance for both you and them.) – Steve Summit Oct 18 '19 at 13:03
  • @SteveSummit It's not just me but C11 annex K explicitly recommends us not to use the function. As for fgets tutorials, feel free to contribute to this community wiki FAQ: https://stackoverflow.com/questions/35178520/how-to-read-parse-input-in-c-the-faq – Lundin Oct 18 '19 at 13:08
  • Thanks for the link. I see more and more questioners using the `_s` functions these days, though, so somebody's getting through to them... :-( – Steve Summit Oct 18 '19 at 14:30
  • @SteveSummit Microsoft has been preaching these `_s` functions for some 20 years. And one problem is that they aren't 100% compatible with C11 annex K "bounds checking interface" (which was quite a fiasco). – Lundin Oct 18 '19 at 14:34